Google Map Api v3 drag event on map

Viewed 54096

I am using google map v3 api. I need to detect the drag event on the map. Be it the drag on the map to move to a nearby geographical location or a drag on the marker. I need some javascript function to run when either of the events occur.

4 Answers
google.maps.event.addListener(map, "mouseover", function (e) {
    google.maps.event.addListener(map, "dragend", function () {
        setTimeout(() => {
           console.log(e); // this contains the information about the coordinates
        });
    });
});

event.latLng.lat() and event.latLng.lng() will give you the coordinates (not in pixels, but in GPS).

function initMapModalAdd() {

    function handleMarkerDrag(event) {
        $('#formAddWell input[name=coordinates]').val(`${event.latLng.lat()}, ${event.latLng.lng()}`);
    }

    const mapCenterPos = {lat: -22.232916, lng: -43.109969};

    window.googleMapAdd = new google.maps.Map(document.getElementById('modal-map-add'), {
        zoom: 8, 
        streetViewControl: false, 
        center: mapCenterPos
    });

    const marker = new google.maps.Marker({draggable: true, position: mapCenterPos, map: window.googleMapAdd});
    marker.addListener('drag', (event) => handleMarkerDrag(event));
    marker.addListener('dragend', (event) => handleMarkerDrag(event));
}

in 2021, you can follow official tips https://developers.google.com/maps/documentation/javascript/events#ShapeEvents

const marker = new google.maps.Marker({
    position: myLatlng,
    map,
    title: "Click to zoom",
  });

  map.addListener("center_changed", () => {
    // 3 seconds after the center of the map has changed, pan back to the
    // marker.
    window.setTimeout(() => {
       console.log('position has change')
    }, 3000);
  });
Related