Search code examples
ioscllocationmanagercllocation

Address/Zip Code as NSString to CLLocation


Is there a way to convert a zip code a user enters into a textbox and convert it into a CLLocation? I am trying to compare distance between their current location and either an address or zip code and this would be easy if I can make a CLLocation out of the NSString.


Solution

  • the procedure called geocoding, and that is how it looks if you implement it:

    NString *_address = // any address or postcode
    
    CLGeocoder *_geocoder = [[CLGeocoder alloc] init];
    [_geocoder geocodeAddressString:_address completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            CLPlacemark *_placemark = [placemarks firstObject];
            CLLocation *_location = _placemark.location;
            // ... do whaterver you want to do with the location
        }
    }];
    

    NOTE: the CoreLocation.framework has to be added to your project properly. you may need to handle errors in your final completion-block, I have not added such part to my code above.