我正在使用 Google Map V3 API。我需要检测地图上的拖拽事件,无论是将地图拖动到附近的地理位置还是将标记器拖动。我需要一些 JavaScript 函数在任何事件发生时运行。
Map对象和Marker对象都有drag
事件,不过你可能更想要使用dragend
事件,这样当用户拖动完成时,才会触发相应的操作,而不是在用户拖动时就执行某些操作。
因此,你可以像这样做:
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
});
});
});
在2021年,您可以遵循官方提示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);
});
event.latLng.lat() 和 event.latLng.lng() 将会给你坐标(不是像素,而是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));
}