繁体   English   中英

如何使用 @react-google-maps/api 中的 getCenter 获取当前地图中心坐标?

[英]How can I get the current map center coordinates using getCenter in @react-google-maps/api?

我正在使用来自@react-google-maps/api GoogleMap组件,但似乎无法找到移动后如何获得当前居中的地图坐标(lat & lng)?

通过四处搜索,我发现了这篇文章,它提出了一个类似的问题,但没有一个答案对我有用。 下面是我正在测试的代码。

import { GoogleMap, useLoadScript } from "@react-google-maps/api";

const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
});

export default function Test() {
    return (
        <>
            <GoogleMap
                zoom={8}
                center={{lat: 35.6676095, lng: 139.334863}}
                // onCenterChanged={getCenter} - doesn't work
                // onCenterChanged={getCenter()} - doesn't work
                // onCenterChanged={this.getCenter} - doesn't work
                // onCenterChanged={ (e)=> this.getCenter(e)}  - doesn't work
            >
            </GoogleMap>
        </>
    );
}

地图加载正常,但是一旦我添加了onCenterChanged=道具,一切都会中断,因为显然没有声明getCenter函数。

我想在移动地图后获得一个带有中心坐标的变量或状态。 我在哪里声明它以及如何使用它?

您需要在 onLoad 期间获取地图的实例,然后使用将使用初始值为 null 保存此实例的状态。 在您的onCenterChanged函数中,检查您的地图实例的值是否不为空,然后获取其新中心。 这是使用以下示例代码和代码片段实现的:

import React, { useState } from 'react';
import { GoogleMap } from '@react-google-maps/api';
const defaultLocation = { lat: 11.174036305817275, lng: 76.3754534171875 };

function Map() {
  const [mapref, setMapRef] = React.useState(null);
  const handleOnLoad = map => {
    setMapRef(map);
  };
  const handleCenterChanged = () => {
    if (mapref) {
      const newCenter = mapref.getCenter();
      console.log(newCenter);
    }
  };

  return (
    <GoogleMap
      center={defaultLocation}
      zoom={8}
      onLoad={handleOnLoad}
      onCenterChanged={handleCenterChanged}
      mapContainerStyle={{ width: '100%', height: '88vh' }}
    />
  );
}

export default Map;

暂无
暂无

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

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