我正在使用下面的Google地图代码从使用PHP动态创建的XML文件中检索和绘制多个地址的标记。除了在Google地图信息窗口中显示相应标记的正确信息外,代码正在执行我需要的所有操作。我获取了所有标记的最后一个XML项目/列表的信息。
我一直在寻找并尝试不同的变化来让它发挥作用,但没有运气。
示例XML数据
<?xml version="1.0" encoding="UTF-8"?>
<listings>
<listing>
<address>123 Street</address>
<city>MANOTICK</city>
</listing>
<listing>
<address>456 Street</address>
<city>MANOTICK</city>
</listing>
<listing>
<address>111 Avenue</address>
<city>MANOTICK</city>
</listing>
<listing>
<address>777 Avenue</address>
<city>Ottawa</city>
</listing>
<listing>
<address>333 Street</address>
<city>Manotick</city>
</listing>
</listings>
谷歌地图代码
function initialize ()
{
var myLatLng = new google.maps.LatLng(45.2340684, -75.6287287);
var myOptions =
{
zoom: 10,
mapTypeControl: true,
center: myLatLng,
zoomControl: true,
zoomControlOptions:
{
style: google.maps.ZoomControlStyle.SMALL
},
StreetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('google_map'), myOptions);
var info_window = new google.maps.InfoWindow;
google.maps.event.addListener
(map, 'click',
function ()
{
info_window.close();
});
downloadUrl
('listings.xml',
function (listings_data)
{
var markers = listings_data.documentElement.getElementsByTagName('listing');
var geocoder = new google.maps.Geocoder();
for (var i = 0; i < markers.length; i++)
{
var address = markers[i].getElementsByTagName('address')[0].firstChild.data;
var city = markers[i].getElementsByTagName('city')[0].firstChild.data;
var address_google_map = address + ', ' + city + ', ON';
var info_text = address + '<br />' + city + ' ON';
geocoder.geocode
({'address': address_google_map},
function (results)
{
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener
(marker, 'click',
function()
{
info_window.setContent(info_text);
info_window.open(map, marker);
});
});
}
});
}
答案 0 :(得分:2)
您遇到地理编码器的异步性质问题,如果添加许多地址,您将遇到地理编码器配额/速率限制的问题(特别是因为您的代码没有查看地理编码器的返回状态)
所有这些问题都是相关的:
最简单的解决方案是使用函数闭包将对地理编码器的调用与返回的结果相关联:
geocodeAddress(xmldata)
{
var address = xmldata.getElementsByTagName('address')[0].firstChild.data;
var city = xmldata.getElementsByTagName('city')[0].firstChild.data;
var address_google_map = address + ', ' + city + ', ON';
var info_text = address + '<br />' + city + ' ON';
geocoder.geocode
({'address': address_google_map},
function (results, status)
{
if (status == google.maps.GeocoderStatus.OK) {
createMarker(results[0].geometry.location, info_text);
} else {
alert("geocode of "+ address +" failed:"+status);
}
});
}
一个createMarker函数,用于将infowindow内容与标记相关联:
function createMarker(latlng, html)
{
var marker = new google.maps.Marker
({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
info_window.setContent(html);
info_window.open(map, marker);
});
}
制作你的for循环:
for (var i = 0; i < markers.length; i++)
{
geocodeAddress(markers[i]);
}