首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >react-google-maps onBoundsChanged

react-google-maps onBoundsChanged
EN

Stack Overflow用户
提问于 2020-04-03 22:21:28
回答 1查看 422关注 0票数 0

我正在努力寻找如何使用onBoundsChanged的简单示例。我注意到在文档https://tomchentw.github.io/react-google-maps中没有解释这个函数

我的简单代码如下所示:

代码语言:javascript
运行
复制
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中获取数据。我需要得到地图中心的纬度和经度,这样我才能更新状态。我认为这是基本的功能,对于已经做到这一点的人来说很容易。非常感谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2020-04-03 22:40:38

您可以添加一个ref属性来访问组件内部的映射。

代码语言:javascript
运行
复制
export class App extends Component {
   state = {
      mapLat: 48.210033,
      mapLng: 16.363449,
    };

   mapRef = React.createRef(); //class scope

将道具添加到map组件

代码语言:javascript
运行
复制
   <GoogleMap
      ref={this.mapRef}
      center={{ lat: this.state.mapLat, lng: this.state.mapLng }}
      zoom={ 13 }
      onBoundsChanged={e => this.handleBoundsChanged(e)}
    />

然后在处理程序中,

代码语言:javascript
运行
复制
handleBoundsChanged = () => {
    const lat= this.mapRef.current.getCenter().lat();
    const lng = this.mapRef.current.getCenter().lng();

    this.setState({
      mapLat: lat,
      mapLng: lng
    });
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61013975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档