[英]My marker is not geocalised on React-Leaflet
我用 React JS 創建了一個鈎子組件,用於在啟動應用程序時對我的標記進行地理定位。 currentLocation 值發生變化,但標記不移動。 你知道為什么?
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;
}
您需要在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);
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.