如何解决我的标记未在 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
函数中设置标记的纬度:
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);
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。