Skip to content Skip to sidebar Skip to footer

Google Maps Polyline Click Between Points

Using Google Maps api 3, I have a polyline with a click event. I need to find out between which two points in the path the user has clicked. Ideally the index of the points. Below

Solution 1:

The following quick and dirty code may not be the best and can surly be optimized, but I work since year with it.

This code i have in the poly click event:

rc = getNearestVertex(poly, event.latLng);x = rc.split(":");  //rc = "index:minDiff"vertIndex = x[0] *1;markerIndexes = vertIndex + ',' +(vertIndex + 1); 

I use it to mark the point before and the point after the marker on the polyline. Following the function:

functiongetNearestVertex(poly, pLatLng) {
    // test to get nearest point on poly to the pLatLng point// click is on poly, so the nearest vertex is the smallest diff betweenvar minDist = 9999999999;
    var minDiff = 9999999999;
    var path = poly.getPath();
    var count = path.length || 0;

    for (var n = 0; n < count - 1; n++) {
        if (n == 0) {
            point = path.getAt(n); 
            dist = g.geometry.spherical.computeDistanceBetween(pLatLng, point);
        }
        //g.geometry.spherical.computeDistanceBetween(aLatLng, bLatLng)var pointb = path.getAt(n + 1);
        distb =  g.geometry.spherical.computeDistanceBetween(pLatLng, pointb);
        distp2p = g.geometry.spherical.computeDistanceBetween(point, pointb);
        var pdiff = dist + distb - distp2p;

        //alert(n + " / " +dist +" + " +distb +" - " +distp2p +" = " +pdiff);if (pdiff < minDiff) {
            minDiff = pdiff.toFixed(3);
            index = n;
        }
        point = pointb;
        dist = distb;
    } //-> end for//alert(index +":" + minDiff);return index +":" + minDiff;
} //-> end of getNearestVertex

Perhaps someone with better js and math. knowledge can jump in and improve the code. However as said it works for me, whereby my track-points for my bicycle tours are very seldom over 2-3-tsd. points

Solution 2:

Try:

    poly.addListener('click', function () {
         getPathVariableCode(poly);
     });
 poly.setMap(map);

    functiongetPathVariableCode(line){
    var codeStr = '  var linePath = [\n';
    var pathArr = line.getPath();
    for (var i = 0; i < pathArr.length; i++){
        codeStr += '    {lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
        if (i !== pathArr.length-1) {
            codeStr += ',\n';
        };

    };

    codeStr += '\n  ];';

    //the coordinates path it´s print on the console of the browserconsole.log (codeStr);
    console.log(pathArr.length);

};

Post a Comment for "Google Maps Polyline Click Between Points"