2011-05-29 146 views
6

我有一個Google Maps V3多段線。我可以檢測整個多段線上的點擊事件,但是我可以使用點擊事件做更高級的事情嗎?谷歌地圖折線:點擊折線部分並返回ID?

我想要做的是檢測折線的哪一部分已被點擊,並在警報中顯示。

routePath = new google.maps.Polyline({ 
    path: routeCoordinates, 
    strokeColor: "#CC33FF", 
    strokeWeight: 3 
});  
routePath.setMap(map); 
google.maps.event.addListener(routePath, 'click', function() { 
    alert(routePath); 
    // TODO: display which section of the polyline has been clicked? 
}); 

有誰知道如何在Google Maps中做到這一點?

謝謝!

回答

8

在click事件上,您可以接收到被點擊的座標的LatLng。但是,因爲這可能不是創建多段線的確切點,所以您需要找到最近的點。您可以使用Google地圖庫中的computeDistanceBetween,或者您可以使用Pythagoras定理,因爲在這種情況下,它應該給您足夠的準確度。

你可以找到關於computeDistanceBetween這裏的更多信息: https://developers.google.com/maps/documentation/javascript/reference#spherical

下面是一個代碼示例,你可以如何與computeDistanceBetween做到這一點。

google.maps.event.addListener(routePath, 'click', function(h) { 
    var latlng=h.latLng; 
    alert(routePath); 
    var needle = { 
     minDistance: 9999999999, //silly high 
     index: -1, 
     latlng: null 
    }; 
    routePath.getPath().forEach(function(routePoint, index){ 
     var dist = google.maps.geometry.spherical.computeDistanceBetween(latlng, routePoint); 
     if (dist < needle.minDistance){ 
      needle.minDistance = dist; 
      needle.index = index; 
      needle.latlng = routePoint; 
     } 
    }); 
    // The closest point in the polyline 
    alert("Closest index: " + needle.index); 

    // The clicked point on the polyline 
    alert(latlng); 

}); 
0

通過距離分析找到最近的點在很多情況下都會失敗,在這種情況下,路徑越過或靠近自身。

你可以用它來確定候選人,但你應該通過比較,如果你使用點擊點分裂連續2個折線點

1

我跑進創建的2號線的cross product和/或dot product確認他們同樣,這裏的問題是我如何處理它: 建立處理程序時:

google.maps.event.addListener(routePath, 'click', function(e) { 
    handelPolyClick(e, this) 
}); 

var handelPolyClick(eventArgs, polyLine) { 
    // now you can access the polyLine 
    alert(polyLine.strokeColor); 
}); 

或者,如果你想訪問通過創建折線變量的相關對象設置:

routePath.car = $.extend({}, cars[1]); // shallow copy of cars[1] 

,那麼你可以從事件訪問你的車:

alert(this.car.color);