首页 > 解决方案 > 如何使用 @react-google-maps/api 中的 getCenter 获取当前地图中心坐标?

问题描述

我正在使用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>
        </>
    );
}

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

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

标签: javascriptreactjsreact-google-maps

解决方案


您需要在 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;

推荐阅读