我有一个HTML页面,其中包含一个谷歌地图信息控件。我能够在html文档中显示一个标记,给出硬编码的静态值。现在我试图从XML外部源文档中获取值。这就是我想要做的,
function initialize(Object) {
var mapOptions = {
center: new google.maps.LatLng(19.314059,84.801407),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
marker:true
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","cd_catalog.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("CD");
for (i = 0; i < x.length; i++) {
var LatLat = x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
var LongLong = x[i].getElementsByTagName("COMPANY")[0].childNodes[0].nodeValue;
var Title = x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
var myLatlng = new google.maps.LatLng(LatLat, LongLong);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: Title
});
}
}
xml文档
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<CATALOG>
<CD>
<TITLE>Ambupa Bauri Street</TITLE>
<ARTIST>56</ARTIST>
<COUNTRY>19.3173287566233</COUNTRY>
<COMPANY>84.8497137612449</COMPANY>
</CD>
<CD>
<TITLE>Anadrigam</TITLE>
<ARTIST>64</ARTIST>
<COUNTRY>19.3128836507433</COUNTRY>
<COMPANY>84.7996238277367</COMPANY>
</CD>
</CATALOG>
我的标签如下,
<body onload="if (onLoad) onLoad(); initialize()">
这不起作用,任何帮助将不胜感激。
答案 0 :(得分:0)
首先,代码将无法正常工作,因为它中存在一些错误。就像你没有提到信息窗口标记的事件监听器一样。
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
您可以从
找到参考Google Maps API v3: auto-center map with multiple markers
或者
http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/
请查看此FIDDLE http://jsfiddle.net/x5R63/
**编辑以获得进一步的回答**
//GET NODE LENGTH
function getNodeLength(nodeName, xmlNode){
return xmlNode.getElementsByTagName(nodeName).length;
}
//GET NODE VALUE
function getNodeValue(nodeName, xmlNode, i){
return xmlNode.getElementsByTagName(nodeName)[i].firstChild.nodeValue;
}
function getExtendedNodeValue(nodeName, xmlNode, i)
{
var node = "";
if(typeof(xmlNode.getElementsByTagName(nodeName)[i]) != "undefined" && xmlNode.getElementsByTagName(nodeName)[i].hasChildNodes())
node = xmlNode.getElementsByTagName(nodeName)[i].firstChild.nodeValue;
return node;
}
function getAttributeValue(i, nodename, data){
return data[i].getAttribute(nodename);
}
现在根据您的情况,您可以使用以下代码:
var len = getNodeLength(xmlDoc,"CD");
for(i=0;i<len;i++)
{
var latLat = getExtendedNodeValue("COUNTRY",xmlDoc,i);
}