How do I calculate the distance between two points

2019-02-03 05:26发布

问题:

This question already has an answer here:

  • Distance between two coordinates with CoreLocation 4 answers

i have latitude and longitude of particular place and i want to calculate the distance so how can i calculate it?

回答1:

CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
NSLog(@"Distance i meters: %f", [location1 distanceFromLocation:location2]);
[location1 release];
[location2 release];

You also need to add CoreLocation.framework to your project, and add the import statement:

#import <CoreLocation/CoreLocation.h>


回答2:

This might not be the most efficient method of doing it, but it will work.

Your two locations specified by latitude and longitude can be considered vectors. Assuming that the coordinates have been converted into cartesion coordinates, calculate the dot product of the two vectors.

Given v1 = (x1, y1, z1) and v2 = (x2, y2, z2), then ...

v1 dot v2 = magnitude(v1) * magnitude(v2) * cos (theta)

Conveniently, the magnitude of v1 and v2 will be the same ... the radius of the earth (R).

x1*x2 + y1*y2 + z1*z2 = R*R*cos(theta)

Solve for theta.

theta = acos ((x1*x2 + y1*y2 + z1*z2) / (R * R));

Now you have angle between the two vectors in radians. The distance betwen the two points when travelling across the surface of earth is thus ...

distance = theta * R.

There is probably an easier way to do this entirely within the context of spherical coordinates, but my math in that area is too fuzzy--hence the conversion to cartesian coordinates.

To convert to cartesian coordinates ...

Let alpha be the latitude, and beta be the longitude.

x = R * cos (alpha) * cos (beta)
y = R * sin (alpha)
z = R * cos (alpha) * sin (beta)

Don't forget that the math function typically deal in radians, and the latitude/longitude deal in degrees.



回答3:

I've cranked through the math, and can now greatly simplify the solution.

Imagine if we spin the earth so that our first vector is at 0 degrees latitude and 0 degrees longitude. The second vector would be at (alpha2 - alpha1) degrees latitude and (beta2 - beta1) degrees latitude.

Since ...

sin(0) = 0 and cos(0) = 1

our dot product simplies to ...

cos(delta_alpha) * cos(delta_beta) = cos(theta)

The rest of the math remains unchanged.

theta = acos (cos(delta_alpha) * cos(delta_beta))
distance = radius * theta

Hope this helps.