谷歌地图API V3地图上的拖动事件

45
我正在使用 Google Map V3 API。我需要检测地图上的拖拽事件,无论是将地图拖动到附近的地理位置还是将标记器拖动。我需要一些 JavaScript 函数在任何事件发生时运行。
4个回答

87

Map对象和Marker对象都有drag事件,不过你可能更想要使用dragend事件,这样当用户拖动完成时,才会触发相应的操作,而不是在用户拖动时就执行某些操作。

因此,你可以像这样做:

google.maps.event.addListener(map, 'dragend', function() { alert('map dragged'); } );
google.maps.event.addListener(marker, 'dragend', function() { alert('marker dragged'); } );

那么,你如何获取新的像素坐标? - Tony Bogdanov
2
获取坐标:类似的问题 - Maxim Yefremov

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

虽然这段代码可能是解决方案,但包括解释真的有助于提高您帖子的质量。请记住,您正在回答未来读者的问题,这些人可能不知道您提出代码建议的原因。 - Neo Anderson
1
Why setTimeout? - Gustavo Contreiras

0

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

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接