[英]Google Maps multiple markers
我有一点问题,我有以下代码,显然一切正常,除了标记的标题。 它始终显示数组列表的最后一个标题。 有人知道为什么这个错误?
码:
$(document).ready(function() {
var options = {
zoom: 7,
center: new google.maps.LatLng(42.19708, 2.19075),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true
};
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
var companys = [
['Giga S.L', 'Plaça de Catalunya, Barcelona'],
['Torre M', 'Plaça d\'Espanya, Barcelona']
];
var address;
var title;
for (var i = 0; i < companys.length; i++) {
address = companys[i][1];
title = companys[i][0];
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location,
title: title // ERROR: ALWAYS THE SAME TITLE
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
先感谢您。
最好的祝福。
geocoder.geocode
有一个回调函数。 这意味着代码以异步方式运行。 您必须重新构建代码以从回调中检索公司标题。
在您的代码中,for循环在geocode
回调返回之前已经完成,这就是您的变量标题设置为最后一个的原因。
解决方法之一是包装调用geocode
在立即调用的函数表达式 (IFFE),在您的变量传递的参数:
(function(address, title) { // the variables are passed in here as function parameters
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location,
title: title
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}(address, title)); // pass in address/title into the IFFE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.