谷歌地图上的Mousedown创建标记并立即拖动它而不释放鼠标按钮

时间:2014-04-14 05:26:32

标签: javascript google-maps-markers draggable

我想做的是假设很简单,但我无法解决这个问题...... 操作步骤如下: 1- Mousedown =>创建标记 2-能够立即拖动此标记而不释放鼠标按钮。这是我找不到......的解决方案。

我的代码看起来像这样:

 var listenerHandle = google.maps.event.addListener(map, 'mousedown', function(e) {

           marker = new google.maps.Marker({
              position: latLng,
              map: map,
              draggable: true
           });

google.maps.event.removeListener(listenerHandle); // to remove the listener 
google.maps.event.trigger(map, 'mouseup'); // this is because the click was first on        the map

// now try to trigger mousedown event because the mouse button must not be released          which should allow the user to move the marker immediatly after having created it.

google.maps.event.trigger(marker, 'mousedown', function(event){
           // process marker mouvements
});

});

这不起作用,因为我必须释放鼠标按钮并将鼠标移动以便能够移动它。 任何解决方案? 许多thxs为您提供帮助

3 个答案:

答案 0 :(得分:2)

一种可能的解决方案是为鼠标移动事件创建额外的事件处理程序,以更新标记位置:

    var listenerHandle = 
            google.maps.event.addListener(map, 'mousedown', function(e) {

        var latLng = e.latLng;

        marker = new google.maps.Marker({
            position: latLng,
            map: map,
            draggable: true
        });

        // to get data about mouse position
        mMoveHandler = google.maps.event.addListener(map, 'mousemove', function(e) {
            marker.setPosition(e.latLng);
        });


        google.maps.event.removeListener(listenerHandle);
    });

此外,地图必须设置为draggable: false,因为在mousedown地图上开始移动。 见example at jsbin

答案 1 :(得分:0)

您可以在鼠标按下时获得标记。但是,要拖动标记,您需要再次单击以抓取标记并拖动它。

答案 2 :(得分:0)

解决方案是为mousemove增加一个监听器以更新标记位置,同时为mouseup增加一个第三监听器,这将删除所有不必要的监听器并重置地图选项:

var listenerHandle = google.maps.event.addListener(map, 'mousedown', function(e) {

        var latLng = e.latLng;

        marker = new google.maps.Marker({
            position: latLng,
            map: map,
            draggable: true
        });
        
        // map should not be deaggable while you move the marker
        map.setOptions({draggable: false});
    
        mousemoveHandle = google.maps.event.addListener(map, 'mousemove', function(e) {
            // update marker position (move marker)
            marker.setPosition(e.latLng);
        });

        mouseupHandle = google.maps.event.addListener(map, 'mouseup', function(e) {
            // remove listeners from map
            google.maps.event.removeListener(listenerHandle);
            google.maps.event.removeListener(mousemoveHandle);
            google.maps.event.removeListener(mouseupHandle);

            // make map draggable again
            map.setOptions({draggable: true});
        });

});

确保已全局声明了Handle变量。