谷歌地图多段线点击检测线号

Google Maps Polyline onclick detect line number

本文关键字:检测 段线点 谷歌地图      更新时间:2023-09-26

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

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..开始),然后我可以使用它来获得适当的数据。

此信息无法通过API获得。

可以使用几何库(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++)
  }