reactjs Map位置在使用中未定义对React瓣叶的影响

amrnrhlw  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(129)

在React Leaflet中加载Map时,我尝试调用位置事件时收到TypeError。当我通过useMapEffects将其设置为单击事件时,它工作。使用useMapEffects的"load"事件不工作(并给出相同的错误)。因此我尝试重构为useEffect。相同的错误。
当试图使其加载时,它会出现此错误。
错误:

Uncaught TypeError: latlng is undefined
    project Projection.SphericalMercator.js:24
    latLngToPoint CRS.js:28
    project Map.js:982
    latLngToLayerPoint Map.js:1004
    _project CircleMarker.js:72
    _reset Path.js:139
    onAdd Path.js:85
    _layerAdd Layer.js:114
    whenReady Map.js:1477
    addLayer Layer.js:172
    addLayer layer.js:9
    React 8
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
...etc

我的组件:

import { useState, useEffect } from "react";
import { useMap, useMapEvents, CircleMarker } from "react-leaflet";

const CurrentLocation = () => {
  const [position, setPosition] = useState(null);

  const map = useMap();

  useEffect(() => {
    map.locate().on("locationfound", (e) => {
      const pos = [e.latlng.lat, e.latlng.lng];
      console.log(pos);
      setPosition(pos);
      map.flyTo(pos, map.getZoom());
    });
  }, [map]);

  return position === null ? null : (
    <CircleMarker position={position}></CircleMarker>
  );
};

export default CurrentLocation;

我的控制台日志实际上生成了一个具有正确坐标的数组。
我的组件在主Map上调用:

...
import CurrentLocation from "../CurrentLocation/CurrentLocation";

const MainMap = (props) => {
  ...

  return (
    <div>
      <MapContainer
        style={{ height: "100vh", width: "100vw" }}
        zoom={12}
        center={centerOfMap}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <CurrentLocation />
        ...
      </MapContainer>
    </div>
cetgtptt

cetgtptt1#

问题出在CircleMarker上,它没有“位置”,只有“中心”。

相关问题