2014-10-07 24 views
1

我创建了一个谷歌地图折线谷歌地图折线的onclick检测行号

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

回答

2

此信息不可通过API获得。

这将有可能使用geometryy库(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++) 
    } 
+0

很好的答案,谢谢。你建议使用单行而不是多段线构建(在我的情况下,我可能需要多达1000行,每个显示地图)? – Enve 2014-10-10 07:27:15

+0

当您使用单线时,它可能会影响性能(尤其是拖动/缩放),但在您需要访问特定片段时看不到更好的方法。 – 2014-10-10 22:38:48