javascript - 如何使用 @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
显然没有声明该函数。
移动地图后,我想获得一个带有中心坐标的变量或状态。我在哪里声明它以及如何使用它?
解决方案
您需要在 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;
推荐阅读
- python-3.x - 将一个字段与包含逗号分隔的 4 个值的 csv 文件的另一个字段进行比较
- android - 找不到类“com.google.android.material.button.MaterialButton”
- python - 根据元组列表中的第二个元素查找具有前 5 个唯一值的所有项目
- nginx - 如何使用 Nginx 访问 control.unit.sock 以安全地代理 Unit API
- r - 如何从函数外部将 lm 对象中的权重作为变量传递,并将列名作为模型表单中的权重引用?
- python - 在 Python 中找到一个元素的总和
- database - 如何获取 Firebase 集合中的所有文档(包括不存在的祖先文档)?
- postgresql - Postgresql 函数:如何处理 [ IN() 或 ANY() ] 中的空值
- javascript - 将图像尺寸分配给文本位置
- mysql - 使用 sql_mode 在 mysql 中禁用 only_full_group_by