Search code examples
reactjsgoogle-mapsgoogle-maps-api-3google-maps-markersreact-google-maps

onPositionChanged handler of gmaps marker scope issue


I try to update the current position of a draggable marker of the react-google-maps wrapper and pass these values back to the parent.
My problem is, that in onMarkerPositionChange this is either the FindLocationMarker class or the marker itself, depending on how the function is invoked.
onPositionChanged={() => this.onMarkerPositionChange()} was my other option.

I need both, the marker for the position and the class for the function in props.
In the provided example, this is the marker. evt is undefined, I know.

How can i provide both, the class scope and the marker, to the function?

class FindLocationMarker extends Component {

  onMarkerPositionChange = (evt) => {
    console.log(evt);
    let lat = this.position.lat();
    let lng = this.position.lng();

    this.props.handleMarkerPositionChange(lat, lng);
  }

  render() {
    return (
      <div>
        <Marker
          position={this.props.position}
          draggable
          onPositionChanged={this.onMarkerPositionChange}
        />
      </div>
      )
  }
}

export default FindLocationMarker;

Solution

  • After a long discussion below I decided to update my answer for future issues with https://github.com/tomchentw/react-google-maps Marker.jsx component.

    If you want to get the position of the marker onPositionChange you need to:

    1. Store the marker in your refs
    2. Listen to the onPositionChange event and then access the position of the marker in your refs.

    Example:

    onPositionChanged() {
        const position = this.marker.getPosition();
    
        // do something with position
    }
    
    render() {
        return <Marker
            onPositionChanged={ ::this.onPositionChanged }
            ref={input => this.marker = input}
        />
    }