谷歌地图Api v3在地图上拖动事件

时间:2011-08-08 11:16:07

标签: google-maps-api-3 drag

我正在使用谷歌地图v3 api。我需要在地图上检测拖动事件。无论是拖动地图移动到附近的地理位置还是拖动标记。我需要一些javascript函数在任何一个事件发生时运行。

3 个答案:

答案 0 :(得分:69)

Map对象和Marker对象都有drag个事件,尽管您可能需要dragend,以便在用户完成拖动时可以执行某些操作,而不是在用户拖动时执行某些操作。

所以你可以这样做:

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

答案 1 :(得分:0)

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

答案 2 :(得分: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));
}
相关问题