Reputation: 171
I have created a hook component with React JS for geolocalised my marker at starting application. The currentLocation value as change but the marker don't move. You know why ?
import { useState, useEffect} from "react";
import { useMap } from "react-leaflet";
import L from "leaflet";
import icon from "./../constants/iconPosition";
export default function LocationMarker() {
const map = useMap();
let [currentPosition, setCurrentPosition] = useState([48.856614, 2.3522219]);
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
setCurrentPosition([position.coords.latitude, position.coords.longitude]);
})
let latlng = currentPosition;
L.marker(latlng, { icon }).addTo(map).bindPopup("You are here!");
map.panTo(latlng);
}
},[]);
return null;
}
Upvotes: 0
Views: 168
Reputation: 11338
You need to set the the latlng of the marker in getCurrentPosition
function:
if (navigator.geolocation) {
let latlng = currentPosition;
var marker = L.marker(latlng, { icon }).addTo(map).bindPopup("You are here!");
map.panTo(latlng);
navigator.geolocation.getCurrentPosition(function (position) {
var pos = [position.coords.latitude, position.coords.longitude];
setCurrentPosition(pos);
marker.setLatLng(pos);
map.panTo(pos);
})
}
Upvotes: 1