我在google地图中实现了多个可拖动标记。现在我遇到的问题是我的坐标似乎没有更新,除了最后一个。
我没有任何错误,只有标记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);
答案 0 :(得分:2)
当您的事件dragstart
,drag
,dragend
被触发时,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());
});
答案 1 :(得分: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