Search code examples
ioscocoa-touchios7cllocation

Calculating Distance between two coordinates using CLLocation


I'm using CLLocationDistance to get the distance between two points, but I'm getting an error when passing my current location in it.

CLLocation *current = [[CLLocation alloc] initWithLatitude:startLocation.coordinate.latitude longitude:startLocation.coordinate.longitude];
CLLocation *itemLoc = [[CLLocation alloc] initWithLatitude:[[[getName objectAtIndex:indexPath.row] objectForKey:@"lat"] doubleValue] longitude:[[[getName objectAtIndex:indexPath.row] objectForKey:@"lon"] doubleValue]];

//Here the current location gives me an error "Initializing cllocation with an expression incompatible format"
CLLocationDistance *itemDist = [itemLoc distanceFromLocation:current];
NSLog(@"Distance: %@", itemDist);

Solution

  • The error you're getting is actually:

    Initializing 'CLLocationDistance *' (aka 'double *') with an expression of incompatible type 'CLLocationDistance' (aka 'double')

    What it's saying is you're initializing itemDist (which you've declared as a CLLocationDistance *) to something that is returning a CLLocationDistance (notice no asterisk).

    CLLocationDistance is not an object.
    It is just a primitive type (specifically double -- see the Core Location Data Types Reference).


    So instead of declaring itemDist as a pointer to a CLLocationDistance, just declare it as a CLLocationDistance (no asterisk):

    CLLocationDistance itemDist = [itemLoc distanceFromLocation:current];
    

    You'll also need to update the NSLog to expect a double instead of an object otherwise it will crash at run-time:

    NSLog(@"Distance: %f", itemDist);