map.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import React, { useEffect, useRef, useState } from "react";
  2. import mapboxgl from "mapbox-gl";
  3. import { useTheme } from "next-themes";
  4. import Image from "next/image";
  5. const LIGHT_STYLE = "mapbox://styles/mapbox/standard";
  6. const DARK_STYLE = "mapbox://styles/mapbox/dark-v10";
  7. const MapComponent: React.FC = () => {
  8. const { theme } = useTheme();
  9. const mapContainerRef = useRef<HTMLDivElement>(null);
  10. const mapRef = useRef<mapboxgl.Map | null>(null);
  11. const [mapLoaded, setMapLoaded] = useState<boolean>(false);
  12. // Create map once
  13. useEffect(() => {
  14. if (mapRef.current) return;
  15. const map = new mapboxgl.Map({
  16. accessToken: process.env.NEXT_PUBLIC_MAPBOX_TOKEN,
  17. container: mapContainerRef.current as HTMLElement,
  18. style: theme === "dark" ? DARK_STYLE : LIGHT_STYLE,
  19. center: [-122.3321, 47.6062],
  20. zoom: 10,
  21. });
  22. map.on("load", () => {
  23. setMapLoaded(true);
  24. });
  25. mapRef.current = map;
  26. return () => {
  27. map.remove();
  28. mapRef.current = null;
  29. };
  30. }, []);
  31. // Switch style without recreating the map
  32. useEffect(() => {
  33. if (!mapRef.current) return;
  34. mapRef.current.setStyle(theme === "dark" ? DARK_STYLE : LIGHT_STYLE);
  35. }, [theme]);
  36. return (
  37. <div className="w-full h-full rounded-3xl overflow-hidden">
  38. {!mapLoaded && (
  39. <Image
  40. alt="Map"
  41. className="w-full h-full object-cover"
  42. height={300}
  43. src="/map.jpg"
  44. width={300}
  45. />
  46. )}
  47. <div ref={mapContainerRef} className="w-full h-full" />
  48. <div
  49. className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2
  50. flex items-center justify-center
  51. w-14 h-14 md:w-20 md:h-20 rounded-full
  52. shadow-lg cursor-pointer bg-blue-400/40 border-2 md:border-4 border-white/80 hover:animate-pulse"
  53. >
  54. <Image
  55. alt="Icon"
  56. className="w-8 h-8 md:w-10 md:h-10"
  57. height={300}
  58. src="https://raw.githubusercontent.com/Tarikul-Islam-Anik/Animated-Fluent-Emojis/master/Emojis/Smilies/Hugging%20Face.png"
  59. width={300}
  60. />
  61. </div>
  62. </div>
  63. );
  64. };
  65. export default MapComponent;