[英]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.