将内容添加到Google Maps Markers时出现问题。这是我的代码:
function loadAttributeMap1() {
geocoder = new google.maps.Geocoder();
mapOptions = {
zoom: 3,
center: new google.maps.LatLng(56.130366,-106.34677099),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas1"), mapOptions);
var markers = /*[[${usersCanada}]]*/; //thymeleaf access to model value
for (var i = 0; i < markers.length; i++) {
var address = markers[i].location;
var content = markers[i].username;
console.log(content);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(content);
addMarkerToMap(markers[i].username, results[0].geometry.location, map);
}
});
}
}
首先console.log(content)
给我这个输出:
[Log] Jack Clinton (googlemaps, line 132)
[Log] jianing xu (googlemaps, line 132)
[Log] Po Tian (googlemaps, line 132)
但是console.log(content)
函数内的geocoder.geocode
总是返回最后一个元素:
[Log] Po Tian (googlemaps, line 132)
[Log] Po Tian (googlemaps, line 132)
[Log] Po Tian (googlemaps, line 132)
我想动态地向标记添加内容,而我现在陷入困境。我将不胜感激。
答案 0 :(得分:0)
我在这里找到了解决方法:Dynamic Markers - Google Maps API - Markers not incrementing with i value in loop
我将功能范围包装器添加到geocoder
:
(function(content) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(content);
addMarkerToMap(content, results[0].geometry.location, map);
}
});
})(content);
它工作正常。希望能帮助某人:)