0

I have three points A, B and P, which are all defined by their longitude/latitude-coordinates.

Now I'm trying to implement an algorithm (see also http://lukagabric.com/distance-from-point-to-line-segment/#comment-60758) in order to calculate the shortest distance between the point P and the line AB:

CLLocationCoordinate2D a;
CLLocationCoordinate2D b;
CLLocationCoordinate2D p;
a.latitude = 3;
a.longitude = 3;
b.latitude = 3.01;
b.longitude = 3.01;
p.latitude = 11;
p.longitude = 11;

CGPoint A = [mapView convertCoordinate:a toPointToView:mapView];
CGPoint B = [mapView convertCoordinate:b toPointToView:mapView];
CGPoint P = [mapView convertCoordinate:p toPointToView:mapView];    

if ((P.x - A.x) * (B.x - A.x) + (P.y - A.y) * (B.y - A.y) < 0) {
    return sqrt(pow((P.x - A.x), 2) + pow((P.y - A.y), 2));
}
else if((P.x - B.x) * (A.x - B.x) + (P.y - B.y) * (A.y - B.y) < 0) {
    return sqrt(pow(P.x - B.x, 2) + pow(P.y - B.y, 2));
}
else {return ABS((P.x * (A.y - B.y) + P.y * (B.x - A.x) + (A.x * B.y - B.x * A.y)) / sqrt(pow(B.x - A.x, 2) + pow(B.y - A.y, 2)));
}

The algorithm should be fine. But probably my transformation from longitude/latitude to cartesian coordinates is wrong. My code uses the build-in objective-c function:

(CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate
           toPointToView:(NSView *)view

That approach seems wrong, because the result (48) is very different to the expected distance (about 1252000 meters). Does anyone know where my transformation from longitude/latitude to cartesian coordinates is wrong? Probably the transformed cartesian coordinates have to be scaled up.

Robert El
  • 1,247
  • 2
  • 10
  • 10
  • 1
    The result is in screen CGPoints so you'd have to convert it to meters somehow. It may be easier to use [this approach](http://stackoverflow.com/a/11172574/467105) (specifically the second sample method that uses _MKMapPoints_). First convert the CLLocationCoordinate2Ds to MKMapPoints (using MKMapPointForCoordinate) and then call the method in the linked answer. –  Dec 22 '14 at 13:51
  • Great, that works perfectly! Thanks for your quick and accurate answer! – Robert El Dec 22 '14 at 14:14

0 Answers0