由于未定义的变量,Google Maps API V3 Marker无法显示

时间:2013-03-04 00:31:53

标签: google-maps google-maps-api-3

我很难通过Google Maps V3 API显示我的标记。

加载页面时出现以下错误 -

TypeError:xml未定义

var markers = xml.documentElement.getElementsByTagName(“marker”);

我尝试用几种不同的方式声明xml变量,但无济于事。

非常感谢任何帮助。

function load() {
  map = new google.maps.Map(document.getElementById("map_canvas"), {
    center: new google.maps.LatLng(37.765558,-122.450867),
    zoom: 11,
    mapTypeId: 'roadmap'
  });
  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP file
  downloadUrl("phpsearch.php", function(data) {
    xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");//<- error occurs right here
//Uncaught TypeError: Cannot read property 'documentElement' of undefined
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var type = markers[i].getAttribute("type");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "<b>" + name + "</b> <br/>" + address;
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon,
        shadow: icon.shadow
      });
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });
}


function downloadUrl(url,callback) {
 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequest;

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request.responseText, request.status);
   }
 };
 request.open('GET', url, true);
 request.send(null);
}

Page在这里:

http://www.students.bl.rdi.co.uk/stu26984/index2.php

以下问题的修复似乎应该有所帮助,但我无法弄清楚为什么我仍被告知该变量未定义。

Cannot load Google Maps Markers from XML variable

1 个答案:

答案 0 :(得分:0)

您的downloadUrl函数会将响应文本而不是响应对象传递给您的回调。您可以更改函数以传递所需的对象。当然,你必须在回复中接收xml。

function downloadUrl(url,callback) {
 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequest;

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request, request.status);//right here
   }
 };
 request.open('GET', url, true);
 request.send(null);
}