多个可拖动标记未更新

Multiple draggable markers not updating

本文关键字:更新 拖动      更新时间:2024-02-06

我在谷歌地图中实现了多个可拖动标记。现在我遇到了一个问题,我的坐标似乎除了上一个坐标之外没有更新。

我没有任何错误,但只有标记10更新了位置和地址。

var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 10,
    center: new google.maps.LatLng(51.012904492831055, 4.3322019042968805),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
for(var i=0;i<10;i++)
{
        var latLng = new google.maps.LatLng(51.012904492831055, 4.3322019042968805);
        var marker = new google.maps.Marker({
            position: latLng,
            title: 'Point ' + (i+1),
            map: map,
            draggable: true
        });
        google.maps.event.addListener(marker, 'dragstart', function() {
            updateMarkerAddress('Dragging...');
        });
        google.maps.event.addListener(marker, 'drag', function() {
            updateMarkerStatus('Dragging...');
            updateMarkerPosition(marker.getPosition());
        });
        google.maps.event.addListener(marker, 'dragend', function() {
            updateMarkerStatus('Drag ended');
            geocodePosition(marker.getPosition());
        });
}
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);

这是变量作用域问题,var marker是循环中的全局变量,并通过循环进行更新,因此最后一个值是在循环结束时设置的。

只需将每个google.maps.event.addListener封装在一个函数中,即

(function(marker){ // Inside this function 'marker' is a local variable.
    google.maps.event.addListener(marker, 'dragstart', function() {
        updateMarkerAddress('Dragging...');
    });
    google.maps.event.addListener(marker, 'drag', function() {
        updateMarkerStatus('Dragging...');
        updateMarkerPosition(marker.getPosition());
    });
    google.maps.event.addListener(marker, 'dragend', function() {
        updateMarkerStatus('Drag ended');
        geocodePosition(marker.getPosition());
    });
})(marker); // Pass the 'global' marker variable as an argument

当您的事件dragstartdragdragend被触发时,marker变量将链接到您创建的最后一个Marker,因为此时您的循环已经结束。

尝试下面的技巧来避免这种情况:

 //..............
 (function(marker){   //added line
    google.maps.event.addListener(marker, 'dragstart', function() {
        updateMarkerAddress('Dragging...');
    });
    google.maps.event.addListener(marker, 'drag', function() {
        updateMarkerStatus('Dragging...');
        updateMarkerPosition(marker.getPosition());
    });
    google.maps.event.addListener(marker, 'dragend', function() {
        updateMarkerStatus('Drag ended');
        geocodePosition(marker.getPosition());
    });
 })(marker);   //added line
 //..............

或者您可以使用this来引用添加了侦听器的标记:

 google.maps.event.addListener(marker, 'drag', function() {
      updateMarkerStatus('Dragging...');
      updateMarkerPosition(this/*instead of 'marker'*/.getPosition());
 });
 google.maps.event.addListener(marker, 'dragend', function() {
      updateMarkerStatus('Drag ended');
      geocodePosition(this/*instead of 'marker'*/.getPosition());
 });