0

我在我的谷歌地图中实现了多个可拖动标记。现在我的问题是我的坐标似乎没有更新,除了最后一个。

我没有得到任何错误,但只有标记 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);
4

2 回答 2

2

当您的 events被触发时,dragstart变量drag将链接到您创建的最后一个,因为那时您的循环已经结束。dragendmarkerMarker

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

 //..............
 (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());
 });
于 2012-07-24T12:32:38.933 回答
2

这是变量范围问题,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
于 2012-07-24T12:33:18.653 回答