Nov 18, 2011 at 9:19 AM
Edited Nov 18, 2011 at 9:23 AM

Hi
Im looking at a way to get the distance from CurrentPosition to the drawn route line...
The idea is that i could detect when i have deviated from the projected route and recalculate a new route.
I found this link which i think gives an equation to do what i wanting to do
http://mathworld.wolfram.com/PointLineDistance2Dimensional.html
Technically i know there is a different formula that will take into account that the earth is round not flat but i think the 2d formula will be accurate enough for what i am trying to do.
any help would be great
I8sy



Hi!
Look at this code (to use the Vector class, which also allows to use "Points" and Vectors with double precision X and Y values, make sure to reference "WindowsBase"):
/// <summary>
/// Returns the point that lies ON a polyline and is closest to a given point.
/// </summary>
/// <param name="points">A List of Vectors/Points that define the polyline.</param>
/// <param name="pos">The given point.</param>
/// <returns>Closest point that lies on the polyline.</returns>
private Vector GetClosestPointOnPolyline(List<Vector> points, Vector pos)
{
SortedDictionary<double, Vector> distances = new SortedDictionary<double, Vector>();
for (int i = 0; i < points.Count  1; i++)
{
double dist;
var point = GetClosestPointOnLinesegment(map, points[i], points[i + 1], pos, out dist);
if (!distances.ContainsKey(dist))
distances.Add(dist, point);
}
return distances.First().Value;
}
/// <summary>
/// Returns the closest Point ON a line segment defined by Points A and B to a given point P, and gets the distance to this point
/// </summary>
/// <param name="A">The Startpoint of the linesegment</param>
/// <param name="B">The Endpoint of the linesegment</param>
/// <param name="P">The given point.</param>
/// <param name="distance">The distance from the line segment to P</param>
/// <returns>Vector (Point) that lies on the linesegement and is closest to P.</returns>
public static Vector GetClosestPointOnLinesegment(GMapEnhanced.Map map, Vector A, Vector B, Vector P, out double distance)
{
Vector AP = P  A;
Vector AB = B  A;
double ab2 = AB.LengthSquared;
double ap_ab = Vector.Multiply(AP, AB);
double t = ap_ab / ab2;
if (t < 0.0f)
t = 0.0f;
else if (t > 1.0f)
t = 1.0f;
Vector closestPoint = A + AB * t;
//Don't use this Length with Lat/Long coordinates!
//distance = (closestPoint  P).Length;
distance = map.MapProvider.Projection.GetDistance(new GMap.NET.PointLatLng(P.Y, P.X), new GMap.NET.PointLatLng(closestPoint.Y, closestPoint.X));
return closestPoint;
}



Hi Xandolph
Thanks for your reply
I just have a question in how to apply the above code
How do i convert the PointLatLng to a Vector? ( the whole Vector thing is throwing me big time :)
Thanks I8sy



never mind i figured it out
Vector currentV = new Vector(Mainmap.Position.Lat, Mainmap.Position.Lng);
the code works great
Thanks for that

