Wednesday, August 22, 2012

Calculating Distance between two locations

In this section, i will show you the easy way of calculating distance between the any of two locations in meters or miles. First of all, we need to have the Longitude and Latitude of those locations to calculate their distance, and for getting latitude and longitude please have a look at MapKit framework and tutorials.
Here i assume we have the required longitude and latitude of those two locations.
For example:
Location 1 ->  double  long1 = -117.321570;   double  lat1 = 33.115120;
Location 2 ->  double  long2 = -122.406417;   double  lat2 = 37.785834;
Now, making CLLocation object for both locations;
CLLocation *location1 = [[CLLocation alloc] initWithLatitude: lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude: lat2 longitude:long2]; 
NSLog(@"LOC1  = %f, %f", location1.coordinate.latitude,  location1.coordinate.longitude);
NSLog(@"LOC2 = %f, %f", location2.coordinate.latitude, location2.coordinate.longitude);
// now calculating the distance using inbuild method distanceFromLocation:
 float distInMeter = [location1 distanceFromLocation:location2]; // which returns in meters
//converting meters to mile
float distInMile = 0.000621371192 * distInMeter;
NSLog(@"Actual Distance in Mile : %f",distInMile);

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. how can we move user location to destination with draw polyline?i want show in google map direction to move user location to destination with polyline .any idea than let me know

    ReplyDelete