我想为每个标记设置不同的图标。 我的代码有问题。仅使用数组的最后一项。 如果查询数组有3个项目,则所有3个标记都将具有3.png图标。
感谢您的帮助!
var img = new Array();
img.push("'images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png", "images/6.png", "images/7.png", "images/8.png", "images/9.png");
var myOptions = {
scaleControl: true,
streetViewControl: false,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
var markers = new Array(query.length);
for (i=0;i<query.length;i++)
{
var geocoder = new google.maps.Geocoder();
var address = query[i];
var image = new google.maps.MarkerImage(
img[i],
new google.maps.Size(24,24),
new google.maps.Point(0,0),
new google.maps.Point(24,24)
);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
markers[i] = new google.maps.Marker({
title:"Marker "+i,
icon: image,
map: map,
position: results[0].geometry.location
});
markers[i].setMap(map);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
}
google.maps.event.addDomListener(window, 'load', initialize);
答案 0 :(得分:1)
访问Google的地理编码服务是异步的
这可以解决您的问题,
var img = new Array();
img.push("'images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png", "images/6.png", "images/7.png", "images/8.png", "images/9.png");
var myOptions = {
scaleControl: true,
streetViewControl: false,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
var markers = new Array(query.length);
var images = new Array(query.length);
for (i=0;i<query.length;i++)
{
var geocoder = new google.maps.Geocoder();
var address = query[i];
var image = new google.maps.MarkerImage(
img[i],
new google.maps.Size(24,24),
new google.maps.Point(0,0),
new google.maps.Point(24,24)
);
images[i] = image;
geoCode(i);
};
function geoCode(i){
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
markers[i] = new google.maps.Marker({
title: results[0].formatted_address,
icon: images[i],
map: map,
position: results[0].geometry.location
});
markers[i].setMap(map);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
答案 1 :(得分:0)
似乎在传递给i
的回调中总是得到相同的geocode
。
您可能想尝试像suggested一样的解决方案。