CLGeocoder多个地址?

时间:2012-04-13 09:26:23

标签: objective-c ios xcode geocoding block

我需要对两个不同的地址进行地理编码,但我需要将结果放在相同的范围/方法中。如何在同一个块中引导相同的变量location1location2。 这是我目前的代码......

 - (IBAction)calculateDistance {
    [textFieldDestination resignFirstResponder];
    NSString *origin = [textFieldOrigin text];
    if (origin) {
        CLGeocoder *geoCode = [[CLGeocoder alloc] init];

        [geoCode geocodeAddressString:origin completionHandler: ^(NSArray *placemarks, NSError *error) {
            if (!error) {
                CLPlacemark *place = [placemarks objectAtIndex:0];
                CLLocation *location = place.location;
                CLLocation *location1 = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            } else {
                NSString *string = [NSString stringWithFormat:@"%@ - also make sure you have inputted a valid city", [error localizedDescription]];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:string delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [alert show];
            }
        }]; 
    }

    NSString *destination = [textFieldDestination text];
    if (destination) {
        CLGeocoder *geoCode2 = [[CLGeocoder alloc] init];

        [geoCode2 geocodeAddressString:destination completionHandler:^(NSArray *placemarks, NSError *error) {
            if (!error) {
                CLPlacemark *place = [placemarks objectAtIndex:0];
                CLLocation *location = place.location;
                CLLocation *location2 = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            } else {
                NSString *string = [NSString stringWithFormat:@"%@ - also make sure you have inputted a valid city", [error localizedDescription]];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:string delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [alert show];
            }
        }]; 
    }

    CLLocationDistance distanceM = [location1 distanceFromLocation:location2];  // obviously error so you can see that I need location1 and location2 in the same block.... but how!?  
    [metreDistance setText:[NSString stringWithFormat:@"%f", distanceM]];
}

1 个答案:

答案 0 :(得分:1)

我发现了如何实现这一目标。对于每个地理编码块,我指向具有特定参数的方法。非常简单,只需要使用逻辑!