我的标记未在 React-Leaflet 上进行地理定位
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
函数中设置标记的经纬度:
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);
})
}
我已经使用 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);
})
}