简体   繁体   中英

react-google-maps onBoundsChanged

I am struggling to find a simple example on how to use onBoundsChanged. I noticed that this function is not explained in the documentation 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. I need to get map center latitude and longitude so I can update the 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.

export class App extends Component {
   state = {
      mapLat: 48.210033,
      mapLng: 16.363449,
    };

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

Add the prop to map component

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM