I have managed to get the co-ordinates for 2 cities using GLGeocoder geocodeAddressString

Having retrieved this 2 city co-ordinates from their names, I want to calculate the distance between them. However Im facing an issue in that the CLLocationDistance runs before the geocodeAddressString.

How do i ensure the distance is only calculated AFTER the city locations have?

Please see my code below:

__block CLLocation *depLocation;
__block CLLocation *arrLocation;

CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@"Birmingham" completionHandler:^(NSArray* placemarks, NSError* error){
    for (CLPlacemark* aPlacemark in placemarks)
    {

        depLocation = [[CLLocation alloc]
                       initWithLatitude:aPlacemark.location.coordinate.latitude
                       longitude:aPlacemark.location.coordinate.longitude];

    }
}];

CLGeocoder *geocoder2 = [[CLGeocoder alloc] init];
[geocoder2 geocodeAddressString:@"Amritsar" completionHandler:^(NSArray* placemarks2, NSError* error){
    for (CLPlacemark* aPlacemark2 in placemarks2)
    {

        arrLocation = [[CLLocation alloc]
                       initWithLatitude:aPlacemark2.location.coordinate.latitude
                       longitude:aPlacemark2.location.coordinate.longitude];

    }
}];

CLLocationDistance distanceXYZ = [depLocation distanceFromLocation:arrLocation];
NSString *distanceLabel = [NSString stringWithFormat:@"Distance to point %4.0f m.", distanceXYZ];
有帮助吗?

解决方案

Simple answer would be to nest all their completion blocks. Copy all the geoCoder2 stuff and put it in geocoder completion block, then copy distanceXYZ and distanceLabel in to the completion block of geocoder2

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top