javascript - Which segment of a polyline was clicked? -


i have set sample polyline 5 segments, , i'm allowing new markers created when user clicks on polyline.

i'd know if there's foolproof way determine whether new marker between markers 0 , 1, or 1 , 2 ... or between 4 , 5. i've considered checking if new marker inside bounding box, , point-in-line formulas, neither 100% precise.

as google maps uses mercator projection projecting gps coordinates, can't use 'line equation' gps coordinates, because projection not linear gps points.but instead can use world coordinates linear. here have used parametric form of line equation check whether point on segment:

function ispointonsegment( map, gpspoint1, gpspoint2, gpspoint ){      var p1 = map.getprojection().fromlatlngtopoint( gpspoint1 );      var p2 = map.getprojection().fromlatlngtopoint( gpspoint2 );      var p = map.getprojection().fromlatlngtopoint( gpspoint );      var t_x;      var t_y;      //parametric form of line equation is:      //--------------------------------      //      x = x1 + t(x2-x1)      //      y = y1 + t(y2-y1)       //--------------------------------      //'p' on [p1,p2] segment,if 't' number [0,1]      //-----case 1----      //      x = x1      //      y = y1      //---------------      if( p2.x-p1.x == 0 && p2.y-p1.y == 0){         return p.x == p1.x && p.y == p1.y;      }else       //-----case 2----      //      x = x1      //      y = y1 + t(y2-y1)      //---------------      if( p2.x-p1.x == 0 && p2.y-p1.y != 0){         t_y = (p.y - p1.y)/(p2.y-p1.y);         return p.x == p1.x && t_y >= 0 && t_y <= 1;      }else      //-----case 3----      //      x = x1 + t(x2-x1)      //      y = y1       //---------------      if( p2.x-p1.x != 0 && p2.y-p1.y == 0){         t_x = (p.x - p1.x)/(p2.x-p1.x);         return p.y == p1.y && t_x >= 0 && t_x <= 1;      }      //-----case 4----      //      x = x1 + t(x2-x1)      //      y = y1 + t(y2-y1)       //---------------      t_x = (p.x - p1.x)/(p2.x-p1.x);      t_y = (p.y - p1.y)/(p2.y-p1.y);      return ( t_x == t_y && t_x >= 0 && t_x <= 1 && t_y >= 0 && t_y <= 1); }  

by having clicked point , segments of polyline, use above implemented function , retrieve segment looking for.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -