【问题标题】:Google Map Api v3 drag event on map地图上的 Google Map Api v3 拖动事件
【发布时间】:2011-10-22 07:37:59
【问题描述】:

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

【问题讨论】:

    标签: google-maps-api-3 drag


    【解决方案1】:

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

    所以你可以这样做:

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

    【讨论】:

    • 那么如何获得新坐标,以像素为单位?
    • 获取坐标:similar question
    【解决方案2】:
    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
            });
        });
    });
    

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • 为什么要设置超时?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2012-10-02
        • 1970-01-01
        • 1970-01-01
        • 2015-08-16
        • 2013-07-10
        • 2011-11-05
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多