gpt4 book ai didi

javascript - 谷歌地图多个标记

转载 作者:行者123 更新时间:2023-12-02 18:18:56 24 4
gpt4 key购买 nike

我有一个小问题,我有以下代码,显然除了标记标题之外一切正常。它始终显示数组列表的最后一个标题。有人知道为什么会出现这个错误吗?

代码:

$(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);
}
});
}
});

提前谢谢您。

致以诚挚的问候。

最佳答案

解决此问题的一种方法是将对 geocode 的调用包装在 immediately-invoked function expression 中。 (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

关于javascript - 谷歌地图多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19026704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com