I want to put facility to display distance between two places selected by user.
Is there any sample source code / service available to do so?
Thanks in advance.
I want to put facility to display distance between two places selected by user.
Is there any sample source code / service available to do so?
Thanks in advance.
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.
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.
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
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
}