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.
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'); } );
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);
});
精彩评论