这是我的HTML代码.我试着在标记上添加一个infowindow,但它不想工作.我的数据是从“Alle_Ortswahlen.page1.xml”文件加载的.
有谁知道如何将infoWindow添加到每个标记?
有谁知道如何将infoWindow添加到每个标记?
<script type="text/javascript"> google.load('maps','3',{ other_params: 'sensor=false' }); google.setOnLoadCallback(initialize); function initialize() { var stack = []; var center = new google.maps.LatLng(48.136,11.586); var options = { 'zoom': 5,'center': center,'mapTypeId': google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"),options); GDownloadUrl("Alle_Ortswahlen.page1.xml",function(doc) { var xmlDoc = GXml.parse(doc); var markers = xmlDoc.documentElement.getElementsByTagName("ROW"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("Field4")); var lng = parseFloat(markers[i].getAttribute("Field6")); var marker = new google.maps.Marker({ position : new google.maps.LatLng(lat,lng),map: map,title:"This is a marker" }); stack.push(marker); } var mc = new MarkerClusterer(map,stack); }); } </script>
解决方法
在for循环之前,创建一个空的infowindow对象.
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker,'click',(function(marker,i) { return function() { infowindow.setContent("You might put some content here from your XML"); infowindow.open(map,marker); } })(marker,i));
将回调参数传递给addListener方法时会发生一些关闭魔法.如果您不熟悉它,请看这里:
Mozilla Dev Center: Working with Closures
所以,你的代码应该是这样的:
google.load('maps',{ other_params: 'sensor=false' }); google.setOnLoadCallback(initialize); function initialize() { var stack = []; var center = new google.maps.LatLng(48.136,11.586); var options = { 'zoom': 5,'mapTypeId': google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"),options); var infowindow = new google.maps.InfoWindow(); GDownloadUrl("Alle_Ortswahlen.page1.xml",function(doc) { var xmlDoc = GXml.parse(doc); var markers = xmlDoc.documentElement.getElementsByTagName("ROW"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("Field4")); var lng = parseFloat(markers[i].getAttribute("Field6")); var marker = new google.maps.Marker({ position : new google.maps.LatLng(lat,title:"This is a marker" }); google.maps.event.addListener(marker,i) { return function() { infowindow.setContent("You might put some content here from your XML"); infowindow.open(map,marker); } })(marker,i)); stack.push(marker); } var mc = new MarkerClusterer(map,stack); }); }