MCPcopy Create free account
hub / github.com/Seanium/ChatMap / initializeMap

Function initializeMap

components/client-map.tsx:37–98  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

35 let isActive = true; // Flag to manage async operations for mounted component
36
37 const initializeMap = async () => {
38 try {
39 const Leaflet = (await import("leaflet")).default; // Dynamically import Leaflet
40 if (!isActive || !mapContainer.current) return;
41
42 // Fix Leaflet icon issues
43 if (Leaflet.Icon && Leaflet.Icon.Default && Leaflet.Icon.Default.prototype) {
44 delete (Leaflet.Icon.Default.prototype as any)._getIconUrl;
45 Leaflet.Icon.Default.mergeOptions({
46 iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
47 iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
48 shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
49 });
50 }
51
52 // Defensive check: if the container DOM node already has leaflet's internal ID
53 if ((mapContainer.current as any)._leaflet_id) {
54 console.warn(
55 "Leaflet map container already had _leaflet_id. This might indicate an incomplete cleanup from a previous instance or a StrictMode interaction."
56 );
57 // Attempt to remove any existing map instance on this container before creating a new one
58 // This is a more aggressive cleanup for problematic scenarios.
59 if (mapRef.current) {
60 mapRef.current.remove();
61 mapRef.current = null;
62 }
63 // Try to clear the id, though this is delving into Leaflet internals
64 delete (mapContainer.current as any)._leaflet_id;
65 }
66
67 const newMapInstance = Leaflet.map(mapContainer.current).setView([35, 105], 4);
68 mapRef.current = newMapInstance; // Store new map instance in ref
69
70 if (!isActive) {
71 newMapInstance.remove(); // Clean up if component unmounted during init
72 mapRef.current = null;
73 return;
74 }
75
76 Leaflet.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
77 attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
78 maxZoom: 19,
79 }).addTo(newMapInstance);
80
81 const leafletMarkersLayer = Leaflet.layerGroup().addTo(newMapInstance);
82
83 // Manage global window properties carefully if they are essential
84 (window as any).leafletMap = newMapInstance; // For existing compatibility
85 (window as any).leafletMarkersLayer = leafletMarkersLayer;
86 (window as any).L = Leaflet;
87
88 setMapInstance(newMapInstance);
89 setIsMapInitialized(true); // Mark as initialized
90
91 } catch (error) {
92 if (isActive) {
93 console.error("Error initializing map:", error);
94 setMapError("初始化地图时出错。请检查控制台获取更多信息。");

Callers 1

ClientMapFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected