我正在尝试通过 XML 文件中的城市和国家/地区名称在我的页面上的 Google 地图上实现标记。不幸的是,我似乎无法获得包含国家/地区对象的全局数组 (countryList),以便在 XML 解析器之外保持填充。在解析器中使用警报,我可以看到它包含 35 个项目,但在它之外有 0 个。我正在寻找一些见解,但我认为它与加载这些函数的顺序有关. 由于该数组不包含任何项目,因此没有城市可用于填充地图标记。
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "countries.xml",
dataType: "xml",
success: parseXML
});
});
var countryList = [];
function parseXML(xml) {
$(xml).find("country").each(function() {
var name = $(this).find("name").text();
var capital = $(this).find("capital").text();
countryList.push(new CountryObject(name, capital));
});
//alert(countryList.length); this shows a count of 35`enter code here`
}
//alert(countryList.length); this shows a count of 0
function CountryObject(name, capital) {
this.name = name;
this.capital = capital;
}
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow = new google.maps.InfoWindow({
content: ''
});
//plot initial point using geocode instead of coordinates (works just fine)
function initialize() {
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds ();
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { 'address': 'Toronto Canada'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
plotMarkers();
}
var locationsArray = [];
for (var j = 0; j < countryList.Length; j++) {
var loc = countryList[j].capital + ' ' + countryList[j].name;
locationsArray[j] = [countryList[j].capital, loc];
}
function plotMarkers(){
var i;
for(i = 0; i < locationsArray.length; i++){
codeAddresses(locationsArray[i]);
}
}
function codeAddresses(address){
geocoder.geocode( { 'address': address[1]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(address[0]);
infowindow.open(map, this);
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
编辑:我希望通过使用 countryList 数组中收集的信息来使用 locationsArray 填充标记(而不是对大多数在线示例使用的值进行硬编码)。但是,我不太明白我缺少什么来保持 countryList 的填充,并且除了我在 SO 上找到的内容之外,我对同步与异步不太熟悉。