javascriptreactjsgoogle-mapsgoogle-map-react

Is there a way to get the coordinates from this draggable marker using google-map-react?


I have made the marker so it is draggable on the map. I am trying to get the coordinates from the marker though so I can save them into my database. Below is the code , is there a function that I can get the coordinates from when the marker has been dragged. Or should I use another google maps react library.

import React, {Component, useCallback} from "react";
import GoogleMapReact from "google-map-react";

class Map extends Component {
  loadMap = (map, maps) => {

    let marker = new maps.Marker({
      position: { lat: 40.856795, lng: -73.954298 },
      map,
      draggable: true,

    });
  };
  

  render() {
    return (
      <div style={{ height: "400px", width: "100%" }}>
        <GoogleMapReact
          bootstrapURLKeys={{ key: "key here" }}
          defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
          defaultZoom={10}
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={({ map, maps }) => this.loadMap(map, maps)}

        >
        </GoogleMapReact>
      </div>
    );
  }
}

export default Map;

Solution

  • You are using the google api for the marker so you can use the marker docs.

    Specifically you should use the dragend event

    Something like

    handleDragEnd = (event) => {
      console.log(event.latLng);
    }
    
    loadMap = (map, maps) => {
      let marker = new maps.Marker({
        position: { lat: 40.856795, lng: -73.954298 },
        map,
        draggable: true,
      });
      marker.addListener('dragend', this.handleDragEnd);
    };