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.
Asked
Active
Viewed 5.5k times
4 Answers
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'); } );
-
So how do you get the new coordinates, in pixels? – Tony Bogdanov Jan 11 '13 at 16:20
-
2to get coordinates: [similar question](http://stackoverflow.com/questions/5290336/getting-lat-lng-from-google-marker) – Maxim Yefremov Jul 30 '13 at 05:09
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
});
});
});

AdefemiGreat
- 23
- 1
-
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));
}

Gustavo Contreiras
- 483
- 3
- 9
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);
});

Alauddin Afif Cassandra
- 481
- 6
- 10