谷歌地图折线:点击折线的某一部分并返回ID?

8

我有一个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?
 });

有人知道如何在Google Maps中完成这个操作吗?谢谢!

我甚至无法触发点击事件,我已经尝试像你一样添加元素,也直接在折线上添加,我做错了什么? - Michael
3个回答

12

在点击事件中,您可以收到被点击坐标的经纬度。但是,由于该位置可能不是创建折线的精确点,因此您需要找到最接近的点。您可以使用Google Maps库中的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);

 });

4
我遇到了同样的问题,以下是我处理它的方法: 在设置处理程序时:
google.maps.event.addListener(routePath, 'click', function(e) {
    handlePolyClick(e, this)
});

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

如果您想访问相关对象集,请通过在polyLine上创建变量来设置它:

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

然后您可以从事件中访问您的汽车:

alert(this.car.color);

这并没有告诉你点击的是折线的哪个部分...是吗? - Michael
当您想要扩展折线属性时,这个功能非常完美。我之前不知道使用 $.extend 是相当巧妙的! - user6743474

2
通过距离分析找到最近的点在许多情况下会失败,特别是当路径交叉或靠近自身时。您可以使用它来识别候选点,但应通过比较使用点击点分割两个连续折线点创建的2条线的叉积和/或点积来确认它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接