如何使用React-leaflet v3在地图加载时将地图设置为地理位置

3

你好,我希望能够加载地图并使用地理定位坐标。 目前,我的地图已经在一个定义好的中心点上加载,当发生onClick事件时,视图将设置为地理定位位置。 我希望在第一次加载地图时就实现这个效果。 以下是我的代码:

...
const Maps = () => {
// visitor geoLocalisation on the Map
  function LocationMarker() {
    const [position, setPosition] = useState(null);

    const map = useMapEvents({
      click() {
        map.locate();
      },
      locationfound(e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
      },
    });

    return position === null ? null : (
      <Marker
        position={position}
        icon={visitorIcon}
      >
        <Popup>You are here</Popup>
      </Marker>
    );
  }

  return (

    <MapContainer
      center={[48.856614, 2.3522219]}
      zoom={13}
      scrollWheelZoom
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />

      <LocationMarker />

   </MapContainer>

  );
}
2个回答

3

用 useEffect 替换 useMapEvents,在组件挂载时触发。使用 map.locate().on("locationfound") 事件来触发地理位置定位。

function LocationMarker() {
    const [position, setPosition] = useState(null);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
      });
    }, []);

    return position === null ? null : (
      <Marker position={position} icon={visitorIcon}>
        <Popup>You are here</Popup>
      </Marker>
    );
  }

演示


非常感谢你,kboul, 你是React之神! :) - emarubi
谢谢 :) 请接受答案,因为它对您有所帮助。请阅读这篇这篇文章。 - kboul
嗨Kboul,代码运行得非常好,除了控制台中出现的这个警告: at LocationMarker ``` 我查看了React useEffect文档,但我不知道如何创建一个Cleanup函数来取消我的定位函数的订阅。 你能帮我吗? - emarubi
我提供的演示中没有这样的警告。它可能来自您应用程序的另一个部分。 - kboul
但是警告显示在LocationMarker处,所以我想它来自钩子。 我在useEffect中放置了这个函数,它停止了之前由map.locate启动的位置监视。 map.stopLocate(); };但是我仍然收到相同的警告。 - emarubi
显示剩余2条评论

1

最终,我将地图放入依赖项中,并添加了一个清理函数,以避免出现Eslint和React警告。

 function LocationMarker() {
    const [position, setPosition] = useState(null);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
      });
      return function cleanup() {
        map.stopLocate();
      };
    }, [map]);

    return position === null ? null : (
      <Marker position={position} icon={visitorIcon}>
        <Popup>You are here</Popup>
      </Marker>
    );
  }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接