44

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.

Trott
  • 66,479
  • 23
  • 173
  • 212
Maxim Dsouza
  • 1,507
  • 3
  • 19
  • 32

4 Answers4

86

Both Map objects and Marker objects have drag events, although you probably want dragend so that you can do something when a user is done dragging rather than do something while a user is dragging.

So you could do something like this:

google.maps.event.addListener(map, 'dragend', function() { alert('map dragged'); } );
google.maps.event.addListener(marker, 'dragend', function() { alert('marker dragged'); } );
jeff
  • 8,300
  • 2
  • 31
  • 43
Trott
  • 66,479
  • 23
  • 173
  • 212
1
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
        });
    });
});
  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Neo Anderson Sep 03 '20 at 19:10
  • 1
0

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));
}
0

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);
  });