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

Sml*_*lok 2 javascript reactjs react-google-maps

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

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

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>
        </>
    );
}
Run Code Online (Sandbox Code Playgroud)

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

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

Pag*_*mag 5

您需要在 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;
Run Code Online (Sandbox Code Playgroud)

  • 这就像一个魅力。唯一的问题是,我的开发环境返回了一些 `_.zf` 对象,而不是像您的示例中那样的纬度长坐标,但是如果我将 `console.log(newCenter)` 更新为 `console.log(newCenter.lat(), newCenter.lng())` 我得到了想要的结果。谢谢你! (3认同)