Search code examples
javascriptreactjsgoogle-maps-react

google-maps-react get marker position on drag end


I'm trying to figure out how to retrieve the marker position when the marker is dragged. I found this : Drag marker event with callback providing lat/long?

and implemented on my app like so:

export class MapContainer extends React.Component {
  onMarkerDragEnd = evt => {
    console.log(evt);
  };

  render() {
    const style = {
      width: "100%",
      height: "300px"
    };

    let lat = this.props.lat;
    let lng = this.props.lng;

    return (
      <Map
        google={this.props.google}
        style={style}
        initialCenter={{
          lat: lat,
          lng: lng
        }}
        zoom={14}
      >
        <Marker
          onClick={this.onMarkerClick}
          draggable={true}
          onDragend={this.onMarkerDragEnd}
          name={"Current location"}
        />
      </Map>
    );
  }
}

the onMarkerDragEnd functions logs an evt object like this:

{onClick: undefined, draggable: true, onDragend: ƒ, name: 
"Currentlocation", map: Zf, …}
draggable: true
google:{maps: {…}}
map: Zf {gm_bindings_: {…}, __gm: uf, gm_accessors_: {…}, mapTypeId: 
"roadmap", center: _.K, …}
mapCenter:{lat: "37.122024", lng: "25.234458"}
name:"Current location"
onClick:undefined
onDragend:ƒ (evt)
__proto__:Object

I tried doing something like this:

onMarkerDragEnd = (evt) => {
  console.log(evt.google.maps.Marker.getPosition().lat());
}

but it return can't get position of undefined

So how do i get the position of the marker from this returned event? Thank you for your help!


Solution

  • The third argument to the onDragend event listener function contains the coordinates of the marker after the drag.

    Example

    class MapContainer extends React.Component {
      state = {
        markers: [
          {
            name: "Current position",
            position: {
              lat: 37.77,
              lng: -122.42
            }
          }
        ]
      };
    
      onMarkerDragEnd = (coord, index) => {
        const { latLng } = coord;
        const lat = latLng.lat();
        const lng = latLng.lng();
    
        this.setState(prevState => {
          const markers = [...this.state.markers];
          markers[index] = { ...markers[index], position: { lat, lng } };
          return { markers };
        });
      };
    
      render() {
        return (
          <Map
            google={this.props.google}
            style={{
              width: "100%",
              height: "300px"
            }}
            zoom={14}
          >
            {this.state.markers.map((marker, index) => (
              <Marker
                position={marker.position}
                draggable={true}
                onDragend={(t, map, coord) => this.onMarkerDragEnd(coord, index)}
                name={marker.name}
              />
            ))}
          </Map>
        );
      }
    }