Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Distance iOS MapKit Using CLLocation

Tags:

ios

mapkit

I am trying to find the distance in miles using the latitude and longitude. I have the following method:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    if(!newLocation) return; 

    if ((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
        (oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
    {



        CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];
        CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];

        CLLocationDistance distance = ([loc2 distanceFromLocation:loc1]) * 0.000621371192;

        //distance = distance; 

        NSLog(@"Total Distance %f in miles",distance);
    }

}

For some reason it prints out something like 5678.32 miles. The location is pretty much stationary and not moving at all.

like image 805
azamsharp Avatar asked Feb 23 '23 14:02

azamsharp


2 Answers

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.(!!!!!)latitude longitude:newLocation.coordinate.(!!!!!)latitude];
like image 117
bealex Avatar answered Mar 03 '23 12:03

bealex


You are initializing loc2 with the latitude of the new location for both the longitude and the latitude:

This line:

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];

Should say:

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];

Hope it helps!

like image 36
Zebs Avatar answered Mar 03 '23 11:03

Zebs