谷歌地图infowindow定位与折线

时间:2014-10-28 23:22:02

标签: javascript google-maps

我有一个包含多条折线的地图,我希望为每条线显示信息窗口。我有infowindow工作,但它没有定位到事件点击应该是。相反,每个窗口显示在同一个地方。似乎无法追查问题的根源。

<script type="text/javascript">

var contentString = "";

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

function initialize() {
  var myLatlng = new google.maps.LatLng(30.695895, -97.354080);
  var mapOptions = {
  zoom: 5,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.TERRAIN,
};

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

downloadUrl("data.xml", function(data)   {

  var xml = xmlParse(data); 
  var polylines = xml.documentElement.getElementsByTagName("polyline");
  var polylineData = new Array();
  for (var i = 0; i < polylines.length; i++) {
    polylineData[i] = {id:polylines[i].getAttribute("id"),
                      name:polylines[i].getAttribute("name"),
                      olat:polylines[i].getAttribute("olat"),
                      olng:polylines[i].getAttribute("olng"),
                      dlat:polylines[i].getAttribute("dlat"),
                      dlng:polylines[i].getAttribute("dlng")}
  }

  for (var j = 0; j < polylineData.length; j++) {
    var path = [
      new google.maps.LatLng(parseFloat(polylineData[j].olat), parseFloat(polylineData[j].olng)),
      new google.maps.LatLng(parseFloat(polylineData[j].dlat), parseFloat(polylineData[j].dlng))
    ];

    var polyline = new google.maps.Polyline({
      path: path,
      strokeWeight: 2
    });


    google.maps.event.addListener(polyline, 'click', (function(event,index){
      return function(){
        infowindow.content = '<div class="infobox" style="width:280px;"><span class="name">' + polylineData[index].name + '</span></div>';
        var point = event.latLng;
        infowindow.setPosition(point);
        infowindow.open(map);
      };

    })(event,j));

    polyline.setMap(map);
  }

});

}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

XML数据如下所示:

<polylines>
    <polyline id="176" name="Line Name" olat="53.545204" olng="-113.369492" dlat="53.545204" dlng="-113.369492"/>
</polylines>

我已经阅读了一些类似的帖子,但到目前为止,这个案例的答案都没有。谢谢!

1 个答案:

答案 0 :(得分:0)

event必须是传递给返回函数的参数:

google.maps.event.addListener(polyline, 'click', (function(index){
//_________________________________________________________^:the index of the item
  return function(event){
//________________^:the event
    infowindow.content = '<div class="infobox" style="width:280px;"><span class="name">' + polylineData[index].name + '</span></div>';
    var point = event.latLng;
    infowindow.setPosition(point);
    infowindow.open(map);
  };

})(j));