我一直在使用一个名为@react-google-maps/api
的库,我想将 map 中心存储为 react 状态,并且我希望用户能够在标记始终位于 map 中心( super 风格位置选择)
问题是当我调用组件的 onCenterChange
时,它返回未定义
以及将 map
实例(在 onLoad
回调中接收)存储为 react 状态后的情况。 map 实例每次都返回完全相同的中心(我猜状态保存是静态的)
<GoogleMap
id={id}
zoom={zoom}
center={center}
options={options}
mapContainerStyle={{ width, height }}
onLoad={m => {
if (!map) setMap(m);
}}
onCenterChanged={e => {
console.log(map);
if (map) {
console.log(parseCoords(map.getCenter()));
}
}}
>
{children}
</GoogleMap>
最佳答案
事实上,onCenterChanged
事件不接受@react-google-maps/api
中的任何参数。 :
onCenterChanged?: () => void;
相反,可以通过 onLoad
事件处理程序检索 map 实例,并以如下状态保存 map 中心:
function Map(props) {
const mapRef = useRef(null);
const [position, setPosition] = useState({
lat: -25.0270548,
lng: 115.1824598
});
function handleLoad(map) {
mapRef.current = map;
}
function handleCenterChanged() {
if (!mapRef.current) return;
const newPos = mapRef.current.getCenter().toJSON();
setPosition(newPos);
}
return (
<GoogleMap
onLoad={handleLoad}
onCenterChanged={handleCenterChanged}
zoom={props.zoom}
center={props.center}
id="map"
>
</GoogleMap>
);
}
这是一个demo它演示了如何在拖动 map 时使标记保持在 map 的中心。
关于javascript - onCenterChange 回调返回未定义的@react-google-maps/api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59818178/