【问题标题】:react-google-maps onBoundsChangedreact-google-maps onBoundsChanged
【发布时间】:2020-07-15 17:54:40
【问题描述】:

我正在努力寻找一个关于如何使用 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;

我不明白如何从地图中获取数据 - onBoundsChanged。我需要获取地图中心的纬度和经度,以便更新状态。我认为这是基本功能,对于已经完成此操作的人来说很容易。非常感谢您提供的所有帮助。

【问题讨论】:

    标签: reactjs react-google-maps


    【解决方案1】:

    您可以添加一个ref 属性来访问组件内的地图。

    export class App extends Component {
       state = {
          mapLat: 48.210033,
          mapLng: 16.363449,
        };
    
       mapRef = React.createRef(); //class scope
    

    将道具添加到地图组件

       <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
        });
      }
    

    【讨论】:

    • 非常感谢您的回答。我已尝试按照您的建议进行更改,但出现错误:'mapRef' is not defined
    • 我的错.. 对答案进行了编辑。需要在 handler 中引用 this.mapRef。
    • @user5421 感谢您的所有帮助,但这似乎也不起作用。我已经复制粘贴了您更新的代码。我不得不承认我注意到了这一点,并认为在你回答之前我会自己解决这个问题。我现在收到的错误消息是:TypeError: this.mapRef.current.getCenter is not a function
    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 2018-04-16
    • 1970-01-01
    • 2019-07-05
    • 2018-07-03
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多