How to calculate distance between two places? Is there any service available by Google Map for iphone?
I want to put facility to display distance between two places sele开发者_StackOverflow中文版cted by user.
Is there any sample source code / service available to do so?
Thanks in advance.
The CoreLocation Framework provides the capability to work out the distance, in meters, between two points:
- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location
You can initialize a CLLocation
object with latitude and longitude:
- (id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
If you have two CLLocation objects, you can just do:
[location1 getDistanceFrom:location2];
However, that's just point-to-point. If you want the distance over a specific route, well, that's a whole other kettle of fish.
This is a task for CLLocation framework. With known coordinates of 2 points you can create (if you don't have them already) 2 CLLocation objects and find a distance between them using
- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location
method.
I am not familiar with iPhone development, but here is the C# code for computing the distance between two points using the Haversine formula:
/// <summary>
/// Computes the distance beween two points
/// </summary>
/// <param name="P1_Latitude">Latitude of first point (in radians).</param>
/// <param name="P1_Longitude">Longitude of first point(in radians).</param>
/// <param name="P2_Latitude">Latitude of second point (in radians).</param>
/// <param name="P2_Longitude">Longitude of second point (in radians).</param>
protected double ComputeDistance(double P1_Longitude, double P1_Latitude, double P2_Longitude, double P2_Latitude, MeasurementUnit unit)
{
double dLon = P1_Longitude - P2_Longitude;
double dLat = P1_Latitude - P2_Latitude;
double a = Math.Pow(Math.Sin(dLat / 2.0), 2) +
Math.Cos(P1_Latitude) *
Math.Cos(P2_Latitude) *
Math.Pow(Math.Sin(dLon / 2.0), 2.0);
double c = 2 * Math.Asin(Math.Min(1.0, Math.Sqrt(a)));
double d = (unit == MeasurementUnit.Miles ? 3956 : 6367) * c;
return d;
}
The MeasurementUnit is defined as:
/// <summary>
/// Measurement units
/// </summary>
public enum MeasurementUnit
{
Miles,
Kilometers
}
It depends on which kind of difference you wanna have between both points. On the map I think you dont wanna the air distance. Then you should check http://iosboilerplate.com/
If you still wanna use the air distance, use Core Location.
- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location
Returns the distance (in meters) from the receiver’s location to the specified location. (Deprecated in iOS 3.2. Use the distanceFromLocation:
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
精彩评论