Google Maps polyline: Click on section of polyline and return ID?

家住魔仙堡 提交于 2019-11-30 07:26:50
Nils

On the click event you can receive a LatLng of the coordinate that was clicked. However, since that will probably not be an exact point that is creating the polyline you need to find the closest point. You can use the computeDistanceBetween in the Google Maps library or you can use Pythagoras theorem as it should give you a good enough accuracy in this case.

You can find more information on computeDistanceBetween here: https://developers.google.com/maps/documentation/javascript/reference#spherical

Here is a code example how you could do it with the 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);

 });
Dexter Le Blanc Jr.

I ran into the same, issue here is how I dealt with it: when setting up the handler:

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

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

Or if you want to access a related object set it by creating a variable on the polyLine:

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

then you can access your car from the event:

alert(this.car.color);

Finding the closest point by distance analysis will fail in a lot of cases where a path crosses back over or near itself.

You can use it to identify candidates, but you should confirm them by comparing the cross product and/or dot product of the 2 lines created if you use the click point to split 2 consecutive polyline points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!