Google Maps Polyline onclick检测行号

时间:2014-10-07 15:16:34

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

我创建了一个谷歌地图折线

var flightPlanCoordinates = [new google.maps.LatLng(-27.46758, 153.027892), new google.maps.LatLng(37.772323, -122.214897), new google.maps.LatLng(29.46758, 88.027892), new google.maps.LatLng(20.46758, 97.027892), new google.maps.LatLng(17.772323, 78.214897)];
    var flightPath = new google.maps.Polyline({
        path: flightPlanCoordinates,
        strokeColor: "rgba(255,0,0, .5)",
        strokeOpacity: 1.0,
        strokeWeight: 4
    });

我创建了一个事件(例如,单击),它显示一个包含信息的框。示例代码:

google.maps.event.addListener(flightPath, 'click', function(el) {
        var curLat = el.latLng.lat();
        var curLng = el.latLng.lng();
        var myLatlng = new google.maps.LatLng(curLat,curLng);
        infowindow.content = "<div style= ' width: 200px'>STRING HERE<div>";
        infowindow.setPosition(myLatlng);
        infowindow.open(map);
    });

我已全局定义infowindow,因此我可以重新定位它。

现在的问题是,无论我点击它,它总是显示相同的信息。基本上我想要做的是点击行号(从0开始,1 ..),我可以使用它来获取适当的数据。

1 个答案:

答案 0 :(得分:2)

此信息无法通过API获取。

可以使用geometryy-library(isLocationOnEdge)并迭代单行以检测点击发生在哪一行,但我认为为每个段使用单个折线更容易:

  var flightPlanCoordinates = [
    new google.maps.LatLng(-27.46758, 153.027892), 
    new google.maps.LatLng(37.772323, -122.214897), 
    new google.maps.LatLng(29.46758, 88.027892), 
    new google.maps.LatLng(20.46758, 97.027892), 
    new google.maps.LatLng(17.772323, 78.214897)
  ],i=0,infowindow=new google.maps.InfoWindow;


  while(flightPlanCoordinates.length>1){
    (function(i){
      var segment= new google.maps.Polyline({
        path: [flightPlanCoordinates.shift(),flightPlanCoordinates[0]],
        strokeColor: "rgba(255,0,0, .5)",
        strokeOpacity: 1.0,
        strokeWeight: 4,
        map:map
      });
      google.maps.event.addListener(segment, 'click', function(e){
        infowindow.setOptions({map:map,position:e.latLng,content:'Line#'+i});
      });
    })(i++)
  }