sandbox-react/leaflet-js-intg/app/components/map-with-marker.jsx

61 lines
1.7 KiB
JavaScript

import React, { useEffect, useRef, useState } from 'react'
import L, { geoJson } from 'leaflet'
export default function MapWithMarker() {
const [markerPosition, setMarkerPosition] = useState({ lat:42.6944, lng:23.3328 })
const mapRef = useRef(null)
useEffect(() => {
var container = L.DomUtil.get("map");
//https://stackoverflow.com/a/50034912/15078958
//Before initializing map check if the map is already initiated or not
if (container != null) {
container._leaflet_id = null;
}
//TODO Is this an alternative?
//https://stackoverflow.com/a/53836894/15078958
/**map.invalidateSize();*/
/*Instantiates a map object given the DOM ID of a <div> element and optionally an object literal with Map options.*/
//TODO mapRef.current = L.map('map').setView( [42.69751, 23.32415], 16 );
mapRef.current = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer(
"http://{s}.tile.osm.org/{z}/{x}/{y}.png",
{
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 18,
scrollWheelZoom: false,
}).addTo(map);
}, [markerPosition]);
const markerRef = useRef(null)
const customIcon = L.icon({
iconUrl: 'https://unpkg.com/leaflet@1.5.1/dist/images/marker-icon.png',
iconSize: [35,46],
iconAnchor: [17,46]
});
useEffect(() => {
if(markerRef.current)
markerRef.current.setLatLng(markerPosition)
else
markerRef.current = L.marker(markerPosition, {icon:customIcon }).addTo(mapRef.current).bindPopup('Bulgarian National Assembly')
}, [markerPosition, customIcon])
return
<>
<p>WithMarker</p>
<div id='map' style={{ width: '80%' }}></div>
</>
};