[英]react-google-maps onBoundsChanged
我正在努力寻找一个关于如何使用 onBoundsChanged 的简单示例。 我注意到这个 function 在文档https://tomchentw.github.io/react-google-maps
中没有解释
我的简单代码如下所示:
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;
我不明白如何从 map - onBoundsChanged 获取数据。 我需要获取 map 中心纬度和经度,以便更新 state。 我认为这是基本功能,对于已经完成此操作的人来说很容易。 非常感谢您提供的所有帮助。
您可以添加一个ref
属性来访问组件内的 map。
export class App extends Component {
state = {
mapLat: 48.210033,
mapLng: 16.363449,
};
mapRef = React.createRef(); //class scope
将 prop 添加到 map 组件
<GoogleMap
ref={this.mapRef}
center={{ lat: this.state.mapLat, lng: this.state.mapLng }}
zoom={ 13 }
onBoundsChanged={e => this.handleBoundsChanged(e)}
/>
然后在处理程序中,
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.