Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Created February 25, 2023 21:19
Show Gist options
  • Save JenniferFuBook/0bf305371c7d7ba1ae6e227822e1fd79 to your computer and use it in GitHub Desktop.
Save JenniferFuBook/0bf305371c7d7ba1ae6e227822e1fd79 to your computer and use it in GitHub Desktop.
import { useEffect, useRef, useState } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import markerIconPng from 'leaflet/dist/images/marker-icon.png';
import markShadowPng from 'leaflet/dist/images/marker-shadow.png';
function App() {
const [jsonContent, setJsonContent] = useState();
const savedMap = useRef();
const mapId = 'map';
useEffect(() => {
fetch('example.geojson')
.then((data) => data.json())
.then((data) => setJsonContent(data))
.catch((err) => console.log(`Error Reading data ${err}`));
}, []);
useEffect(() => {
if (savedMap.current) {
savedMap.current.off();
savedMap.current.remove();
}
const map = L.map(mapId);
savedMap.current = map;
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}{r}.png', {
attribution:
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
if (jsonContent) {
const geojsonLayer = L.geoJSON(jsonContent, {
pointToLayer(feature, latlng) {
if (feature.properties && feature.properties.icon) {
return L.marker(latlng, {
icon: L.icon(feature.properties && feature.properties.icon),
});
}
return L.marker(latlng, {
icon: L.icon({
iconUrl: markerIconPng,
shadowUrl: markShadowPng,
}),
});
},
onEachFeature(feature, layer) {
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent, {
autoClose: false,
});
}
},
}).addTo(map);
map.fitBounds(geojsonLayer.getBounds());
geojsonLayer.eachLayer((layer) => layer.openPopup());
}
}, [jsonContent]);
return <div id={mapId}></div>;
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment