简体   繁体   English

onCenterChange 回调返回未定义的@react-google-maps/api

[英]onCenterChange callback returns undefined @react-google-maps/api

I have been using a library called @react-google-maps/api and I want to store the map center as react state and I want the user to be able to drag the map while the marker always stays at the center of the map ( uber style location selection)我一直在使用一个名为@react-google-maps/api ,我想将地图中心存储为反应状态,并且我希望用户能够拖动地图而标记始终位于地图的中心( uber风格位置选择)

The Problem is when I call the onCenterChange of the component, it returns me undefined问题是当我调用组件的onCenterChange时,它返回我未定义

and when after store the map instance (recieved on the onLoad callback) as react state.以及在将map实例(在onLoad回调上收到)存储为反应状态之后。 The map instance returns the exact same center everytime (I guess the state save is static)地图实例每次都返回完全相同的中心(我猜状态保存是静态的)

<GoogleMap
        id={id}
        zoom={zoom}
        center={center}
        options={options}
        mapContainerStyle={{ width, height }}
        onLoad={m => {
          if (!map) setMap(m);
        }}
        onCenterChanged={e => {
          console.log(map);
          if (map) {
            console.log(parseCoords(map.getCenter()));
          }
        }}
      >
        {children}
      </GoogleMap>

Indeed, onCenterChanged event does not accept any arguments in @react-google-maps/api :实际上, onCenterChanged事件不接受@react-google-maps/api任何参数:

onCenterChanged?: () => void;

Instead map instance could be retrieved via onLoad event handler and map center saved in state like this:相反,可以通过onLoad事件处理程序检索地图实例,并将地图中心保存在如下状态:

function Map(props) {
  const mapRef = useRef(null);
  const [position, setPosition] = useState({
    lat: -25.0270548,
    lng: 115.1824598
  });

  function handleLoad(map) {
    mapRef.current = map;
  }

  function handleCenterChanged() {
    if (!mapRef.current) return;
    const newPos = mapRef.current.getCenter().toJSON();
    setPosition(newPos);
  }

  return (
    <GoogleMap
      onLoad={handleLoad}
      onCenterChanged={handleCenterChanged}
      zoom={props.zoom}
      center={props.center}
      id="map"
    >
    </GoogleMap>
  );
}

Here is a demo which demonstrates how to keep the marker centered of the map while dragging the map.这是一个演示,它演示了如何在拖动地图时将标记保持在地图的中心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM