单击了多段线的哪一段? [英] Which segment of a polyline was clicked?

查看:28
本文介绍了单击了多段线的哪一段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个 具有五个线段的示例折线,并且我允许新的标记当用户点击多段线时被创建.

I have set up a sample polyline with five segments, and I'm allowing new markers to be created when the user clicks on the polyline.

我想知道是否有一种万无一失的方法来确定新标记是在标记 0 和 1 之间,还是在 1 和 2 之间……或在 4 和 5 之间.我已经考虑过检查新标记是否是边界框内和线中点公式,但都不是 100% 精确.

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

推荐答案

由于 Google 地图使用 墨卡托投影 对于投影 GPS 坐标,您不能对 gps 坐标使用线方程",因为 gps 点的投影不是线性的.但是您可以使用线性的 world 坐标.这里我使用了线方程的参数形式来检查point是否在段上:

As Google Maps uses Mercator Projection for projecting GPS coordinates, you can't use 'line equation' for gps coordinates, because projection is not linear for gps points.But instead you can use world coordinates which are linear. Here I have used parametric form of line equation to 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' is on [p1,p2] segment,if 't' is number from [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 and all segments of polyline, you could use above implemented function and retrieve segment you were looking for.

这篇关于单击了多段线的哪一段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆