Google地图折线:点击折线部分并返回ID?

phi*_*123 7 google-maps polyline google-maps-api-3

我有一个Google Maps V3折线.我可以检测整个折线上的点击事件,但是我可以使用点击事件做更高级的事吗?

我想要做的是检测折线的哪个部分已被点击,并在警报中显示.

 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?
 });
Run Code Online (Sandbox Code Playgroud)

有谁知道如何在谷歌地图中这样做?

谢谢!

Nil*_*ils 11

在click事件中,您可以接收已单击的坐标的LatLng.但是,由于这可能不是创建折线的确切点,因此您需要找到最近的点.你可以在谷歌地图库中使用computeDistanceBetween,或者你可以使用毕达哥拉斯定理,因为在这种情况下它应该给你足够的准确性.

你可以在这里找到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);

 });
Run Code Online (Sandbox Code Playgroud)