A React App that tracks users location , can search places using Mapbox API and can add new markers
A simple map application using React as frontend , Mapbox forward API for search coordinates and LeafletJS for map tiles
Use mapRef to Initialize your Map. Ignore the functions present in leaflet documentation. Some methods like addLayer
is not working in React v18.
const mapRef = useRef();
const initializeMap = () => {
mapRef.current = new L.map("map").setView([0, 0], 13);
L.tileLayer(
`https://api.mapbox.com/styles/v1/misixi/clcedh8kx000b14mr7776gtot/tiles/256/{z}/{x}/{y}@2x?access_token=${process.env.REACT_APP_API_KEY}`,
{
attribution:
"© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>",
}
).addTo(mapRef.current);
mapRef.current.on("moveend", () => {
closeSearchResults();
});
};
Initialize your map everytime using useEffect(). The below method is important else, your app will crash after refresh
useEffect(() => {
//init map
var container = L.DomUtil.get("map");
if (container != null) {
container._leaflet_id = null;
}
initializeMap();
getGeolocations();
}, []);