我可能在这里做了一些愚蠢的事情,但我不明白为什么我的两个标记最终都具有相同的标题。两个标记都以地理编码器的正确位置结束,并显示在不同的位置。
渲染前
function gMapInitialize() {
var myLocs = [<ui:repeat value = "#{LocationBean.locations.address}" var = "loc" varStatus = "loop">
[ "#{loc.name}","#{loc.street}","#{loc.city}","#{loc.state}", "#{loc.zipCode}"]#{!loop.last ? ',' : ''}
</ui:repeat>];
//<![CDATA[
var myOptions = {
center: new google.maps.LatLng(37.212832,-76.750488),
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
for(var i = 0; i < myLocs.length; i++){
var myLoc = myLocs[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,function(results, status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myLoc[0],
zIndex: i
});
}
});
}
}
// ]]>
渲染后:
function gMapInitialize() {
var myLocs = [
[ "Richmond","9 North 3rd Street","Richmond","VA", "23219"],
[ "Hampton Roads","632 North Witchduck Road","Virginia Beach","VA", "23462"]
];
//<![CDATA[
var myOptions = {
center: new google.maps.LatLng(37.212832,-76.750488),
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
for(var i = 0; i < myLocs.length; i++){
var myLoc = myLocs[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,function(results, status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myLoc[0],
zIndex: i
});
}
});
}
}
// ]]>
我是否试图在一个循环中做太多事情?我一直听到一些关于闭包的消息,但对 javascript 很陌生,对此一无所知。
哦,是的:我在每个标记上都有两个名字中的第二个。标记位于正确的位置,但两者都命名为“Hampton Roads”。因此,正确的信息被传递给标题,但好像第一个标题被第二个标题覆盖。
更新好吧,我修复了它,我想我对关闭有了更多的了解。所以主要是循环一直在循环,当函数被调用时,它已经在最后了。因此,即使在下面,每个标记也可能具有相同的 zIndex,我也应该传递“i”。
for(var i = 0; i < myLocs.length; i++){
var myLoc = myLocs[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,addMarkers(myLoc[0]));
}
function addMarkers(myTitle){
return function(results,status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myTitle,
zIndex: i
});
}
};
}