首页 > 解决方案 > 我的标记未在 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;
}

标签: javascriptreactjsleafletreact-leaflet

解决方案


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);
    })
  }

推荐阅读