[英]react-google-maps onBoundsChanged
I am struggling to find a simple example on how to use onBoundsChanged.我正在努力寻找一个关于如何使用 onBoundsChanged 的简单示例。 I noticed that this function is not explained in the documentation
https://tomchentw.github.io/react-google-maps
我注意到这个 function 在文档
https://tomchentw.github.io/react-google-maps
中没有解释
My simple code looks like this:我的简单代码如下所示:
import React, { Component } from 'react';
import { GoogleMap } from '@react-google-maps/api';
export class App extends Component {
state = {
mapLat: 48.210033,
mapLng: 16.363449,
}
handleBoundsChanged = () => {
console.log('BoundsChanged');
// how do I get the center of the map on BoundsChange
// update map center
/*
this.setState({
mapLat: '?',
mapLng: '?'
})
*/
}
render() {
return (
<div>
<GoogleMap
center={{ lat: this.state.mapLat, lng: this.state.mapLng }}
zoom={ 13 }
onBoundsChanged={e => this.handleBoundsChanged(e)}
/>
</div>
);
}
}
export default App;
I do not understand how to get the data from the map - onBoundsChanged.我不明白如何从 map - onBoundsChanged 获取数据。 I need to get map center latitude and longitude so I can update the state.
我需要获取 map 中心纬度和经度,以便更新 state。 I would think this is basic functionality and it is easy for someone who already has done this.
我认为这是基本功能,对于已经完成此操作的人来说很容易。 Thank you so much for all your kind help.
非常感谢您提供的所有帮助。
You can add a ref
prop to access the map inside the component.您可以添加一个
ref
属性来访问组件内的 map。
export class App extends Component {
state = {
mapLat: 48.210033,
mapLng: 16.363449,
};
mapRef = React.createRef(); //class scope
Add the prop to map component将 prop 添加到 map 组件
<GoogleMap
ref={this.mapRef}
center={{ lat: this.state.mapLat, lng: this.state.mapLng }}
zoom={ 13 }
onBoundsChanged={e => this.handleBoundsChanged(e)}
/>
Then in the handler,然后在处理程序中,
handleBoundsChanged = () => {
const lat= this.mapRef.current.getCenter().lat();
const lng = this.mapRef.current.getCenter().lng();
this.setState({
mapLat: lat,
mapLng: lng
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.