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?
 });

有谁知道如何在谷歌地图中做到这一点?

谢谢!

4

3 回答 3

12

在单击事件中,您可以收到被单击坐标的 LatLng。但是,由于这可能不是创建折线的确切点,因此您需要找到最近的点。您可以使用 Google 地图库中的 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);

 });
于 2012-03-19T21:09:10.077 回答
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);
于 2015-04-27T18:22:51.237 回答
1

在很多情况下,当路径越过或靠近自身时,通过距离分析找到最近点会失败。

您可以使用它来识别候选者,但如果您使用点击点分割 2 个连续的折线点,则应通过比较创建的 2 条线的叉积和/或点积来确认它们

于 2014-02-12T18:35:15.757 回答