【问题标题】:How can I get the current map center coordinates using getCenter in @react-google-maps/api?如何使用 @react-google-maps/api 中的 getCenter 获取当前地图中心坐标?
【发布时间】:2023-04-04 09:50:01
【问题描述】:

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

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

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 函数。

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

【问题讨论】:

    标签: javascript reactjs react-google-maps


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 这就像一个魅力。唯一的问题是,我的开发环境返回了一些 _.zf 对象,而不是像您的示例中那样的经纬度坐标,但是如果我将 console.log(newCenter) 更新为 console.log(newCenter.lat(), newCenter.lng()) 我会得到所需的结果。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2013-06-27
    相关资源
    最近更新 更多