2

I tried:

<GoogleMap
  defaultZoom={14}
  center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}}
  onCenterChanged={getCenter()}
/>

Update: I am using a Stateless Functional Component:

const MarkerClustererExampleGoogleMap = withGoogleMap(props => (

    <GoogleMap 
        defaultZoom={14} 
        center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}} 
        onCenterChanged={getCenter()} 
    >
)

But I get the error:

getCenter is undefined.

How to resolve this problem, Thanks.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
cm-brain
  • 39
  • 1
  • 6

3 Answers3

2

You can call functions like getCenter(), getZoom(), getBounds() etc from the map API via a React ref to the map component

Here is a rough example, note this is an untested snippet and should be considered pseudocode, but it hopefully gives you the idea of how to get this set up:

let ref

...

<GoogleMap 
  ref={(mapRef) => ref = mapRef} // bind the ref
  onCenterChanged={() => {
    ref.getCenter() // get the center, zoom, whatever using the ref
  }}
/>

There are more detailed examples of how to do this in the documentation, for example here.

davnicwil
  • 28,487
  • 16
  • 107
  • 123
0

You need to use it like this:

onCenterChanged={this.getCenter}

Note: onCenterChanged is a event, so make sure you defined the binding in the constructor, like this

this.getCenter = this.getCenter.bind(this);

or you can use arrow function also, By Arrow Function:

onCenterChanged={ (e)=> this.getCenter(e)}

Update: You didn't mention that your are using Stateless Functional Component, whenever asking ques, try to provide the complete information.

Check this, how to define the function inside Stateless Functional Component:

var App = () => {

   var click = function() {
      console.log('a');
   }
   
   return(
      <div onClick={click}> Click </div>
   )
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • Oh, I could use like your resolve, but I have stateless component. And my variable "this" is not defined. I use component GoogleMap without variable "this" `const MarkerClustererExampleGoogleMap = withGoogleMap(props => ( ` – cm-brain Apr 20 '17 at 09:06
  • @cm-brain check the updated answer, how to define function inside stateless functional component. Write it in the same way it will work. – Mayank Shukla Apr 20 '17 at 09:18
0

Have a look at the example: Adding a places search box. This part of the code will show you the right path )

handleMapMounted(map) {
  this._map = map;
}

handleBoundsChanged() {
  this.setState({
  bounds: this._map.getBounds(),
  center: this._map.getCenter(),
});
}
Taras Yaremkiv
  • 3,440
  • 7
  • 32
  • 54