0

I need to check if a polyline runs under a marker. The marker and polyline should have the same latLng at that point. The problem is that there are multiple markers on my map. I can't seem to figure out how I can get the right polylines selected.

Object of Marker/Polyline:

{  
    latLng:     Array with latLng's,  
    marker:     Leaflet marker/polyline layer object,  
    selected:   boolean  
}

Polylines that crosses a marker contains the same latlng point as the marker, but I can't get the right result. I think it's more a mathematical problem

Image for more info:

https://i.stack.imgur.com/CABjB.png

P.S. Sorry for my bad english

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
  • Take a look at turf.js. It has simple geo-analysis tools. If using plain javascript you could just loop over the geometry in the line layer group. Can you make a plunker. – Cory Silva Mar 31 '15 at 18:37
  • Is it always the starting or ending point of the polyline that crosses the marker? – maRtin Apr 01 '15 at 09:37

1 Answers1

0

You could try this:

markerLatLng = marker.getLatLng()

for(var i = 0; i < latLng.length-1; i++){
    if (isBetween(latLng[i], latLng[i+1], markerLatLng)){
        // marker is between this line segment
        selected = true; //or do what you want to here 
    }
}    

def isBetween(a, b, c){
    crossproduct = (c.lng - a.lng) * (b.lat - a.lat) - (c.lat - a.lat) * (b.lng - a.lng);
    if(Math.abs(crossproduct) > epsilon) return false; //epsilon = 0 for integers, use small number operations on floating point coordinates

    dotproduct = (c.lat - a.lat) * (b.lat - a.lat) + (c.lng - a.lng)*(b.lng - a.lng);
    if(dotproduct < 0) return false;

    squaredlengthba = (b.lat - a.lat)*(b.lat - a.lat) + (b.lng - a.lng)*(b.lng - a.lng);
    if(dotproduct > squaredlengthba) return false;

    return true;
}

Note: Floating point arithmetic errors will give you grief here. Modify epsilon to increase the buffer around the line to which the marker is considered "on the line".

Adapted from this answer by Cyrille Ka

Community
  • 1
  • 1
tayden
  • 570
  • 7
  • 20