【发布时间】:2011-10-22 07:37:59
【问题描述】:
我正在使用谷歌地图 v3 api。我需要检测地图上的拖动事件。无论是在地图上拖动以移动到附近的地理位置,还是在标记上拖动。当任一事件发生时,我需要一些 javascript 函数来运行。
【问题讨论】:
我正在使用谷歌地图 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
});
});
});
【讨论】:
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));
}
【讨论】:
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);
});
【讨论】: