我正在努力寻找如何使用onBoundsChanged的简单示例。我注意到在文档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中获取数据。我需要得到地图中心的纬度和经度,这样我才能更新状态。我认为这是基本的功能,对于已经做到这一点的人来说很容易。非常感谢你的帮助。
发布于 2020-04-03 22:40:38
您可以添加一个ref属性来访问组件内部的映射。
export class App extends Component {
state = {
mapLat: 48.210033,
mapLng: 16.363449,
};
mapRef = React.createRef(); //class scope将道具添加到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
});
}https://stackoverflow.com/questions/61013975
复制相似问题