javascript - 我的标记未在 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);
})
}
推荐阅读
- kubernetes - 如果文件没有更改,如何重新部署(滚动更新)kubernetes 部署
- node.js - 在 DynamoDB 上扫描表的正确方法是什么?
- c# - 不再需要第二个 T-SQL 查询
- intellij-idea - maven子模块中的Groovy Main方法在运行前不会自动编译
- datatable - 无法解析 Cucumber 4.xx 的 JacksonTableTransformer
- matlab - 一旦线条触及预定义正方形的周边,如何停止绘图?
- java - 如何使用 grep 命令从日志文件中捕获相关 ID 以及 java stacktrace 和多行消息
- listview - 如何添加一个位于页面底部并可以使用 ListView 滚动的小部件?
- javascript - ReactJS:使用地图的键渲染对象
- regex - 如何为“大于 10-000-000 且小于 150-000-000”创建匹配的正则表达式模式?