Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Last active March 5, 2023 01:09
Show Gist options
  • Save JenniferFuBook/51b9daba89b04fcf539e65341b4850bb to your computer and use it in GitHub Desktop.
Save JenniferFuBook/51b9daba89b04fcf539e65341b4850bb to your computer and use it in GitHub Desktop.
import { useCallback, useEffect, useRef, useState } from 'react';
import { MapContainer, TileLayer, GeoJSON } from 'react-leaflet';
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 [isMapReady, setIsMapReady] = useState(false);
const mapRef = useRef();
const geojsonRef = useRef();
useEffect(() => {
fetch('example.geojson')
.then((data) => data.json())
.then((data) => setJsonContent(data))
.catch((err) => console.log(`Error Reading data ${err}`));
}, []);
useEffect(() => {
if (mapRef.current && jsonContent) {
mapRef.current.fitBounds(geojsonRef.current?.getBounds());
geojsonRef.current?.eachLayer((layer) => layer.openPopup());
}
}, [isMapReady, jsonContent]);
const pointToLayer = useCallback((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,
}),
});
}, []);
const onEachFeature = useCallback((feature, layer) => {
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent, {
autoClose: false,
});
}
}, []);
return (
<MapContainer
center={[38.907192, -77.036873]}
zoom={10}
ref={mapRef}
whenReady={() => setIsMapReady(true)}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://tile.openstreetmap.org/{z}/{x}/{y}{r}.png"
/>
{jsonContent && (
<GeoJSON
data={jsonContent}
pointToLayer={pointToLayer}
onEachFeature={onEachFeature}
ref={geojsonRef}
/>
)}
</MapContainer>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment