我正在尝试将不同的标记设置为一组地址。我想要一个单独的infowindow。我没有得到信息

时间:2014-10-03 05:04:51

标签: javascript google-maps infowindow marker

我从PHP调用函数(被成功调用)并尝试为每个标记设置infowindows。正在设置标记,但是没有为每个标记设置信息。

相同的代码如下。

var markers = [];
var infowin = [];

function addMarker(address, name, contact, id, x) {
  switch(x) {
    case "domestic":
      icon = "grn-blank";
      break;
    case "plumber":
      icon = "purple-blank";
      break;
    case "laundry":
      icon = "orange-blank";
      break;
    case "carpenter":
      icon = "red-blank";
      break;
    case "milk_vendor":
      icon = "ylw-blank";
      break;
    case "electrician":
      icon = "pink-blank";
      break;
    case "newspaper_vendor":
      icon = "blu-blank";
      break;
  }
  var iconbase = "http://maps.google.com/mapfiles/kml/paddle/";
  var icon = icon + ".png";
  var icons = iconbase + icon ;

  geocoder.geocode({'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        animation: google.maps.Animation.DROP,
        icon: new google.maps.MarkerImage(icons)
      });
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });

  var contentw = "Name: " + name + "\nAddress: " + address + " \nPhone: " + contact + "\nId-Number: " + id;

  var infowindow = new google.maps.InfoWindow({
    content: contentw
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
  });
  markers.push(marker);
  infowin.push(infowindow); 
}

我可以采取哪些措施来避免此问题?

1 个答案:

答案 0 :(得分:0)

您的代码中存在竞争条件。要理解它,请查看以下精简示例。

function addMarker(...) {
  ...
  geocoder.geocode({'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      // This is where you create the marker (in an asynchronous callback)
      var marker = new google.maps.Marker({ ... });
      ...
    }
  });
  ...
  var infowindow = new google.maps.InfoWindow({ ... });

  // This is where you access the marker (in the surrounding function)
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
  });
  ...
}

地理编码请求是异步进行的。因此,在执行回调function(results, status)时,周围的addMarker函数可能已经完成执行。当您尝试访问addMarker变量时,竞争条件发生在marker的末尾。但是,在执行地理编码回调之前,不会分配此变量的值。

要解决此问题,您需要做的就是将信息窗口代码移动到地理编码回调中。

function addMarker(...) {
  ...
  geocoder.geocode({'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var marker = new google.maps.Marker({ ... });
      var infowindow = new google.maps.InfoWindow({ ... });

      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });
      ...
    }
  });
  ...
}

查看JSFiddle上的工作示例。