JayB127
JayB127

Reputation: 83

Getting a parsed and properly formatted address from Google Maps

I'm trying to use Google's Maps API services in my iOS app to convert a string containing an address to a properly parsed and legitimate address. I understand that Google's API doesn't verify that the address is valid; I just need it to parse the string into a full, logical address.

After some digging around on the API's website, the only way I've found to do this is to use the geocoding feature to convert the input string into coordinates, and then use reverse geocoding to convert it back into something I can parse. Is there any way to do this with less overhead? Doing it this way seems a little bit backwards.

Example: 347 N Canon Dr Beverly Hills, CA 90210. Google maps seems like the best choice to intuitively separate the different parts of the address. Otherwise, I run the risk of dealing with issues like 1040 8th street becoming 104 08th street or something like that. I want to be able to type in an address that's mostly formatted correctly and for google to use the API to correct it and return something that I can then pass into a webservice.

Upvotes: 3

Views: 1033

Answers (1)

jscs
jscs

Reputation: 64002

I think that you want NSDataDetector, which is built right in to Cocoa Touch.

It has a subtype, NSTextCheckingTypeAddress, that will attempt to parse addresses for you.

Using one on your example string:

NSString * address = @"347 N Canon Dr Beverly Hills, CA 90210";
NSError * err;
NSDataDetector * addrParser = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress
                                                              error:&err];
__block NSDictionary * addressParts;
if( addrParser ){
    [addrParser enumerateMatchesInString:address
                                 options:0
                                   range:(NSRange){0, [address length]}
                              usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                                  addressParts = [result addressComponents];
    }];
}

NSLog(@"%@", addressParts);

Produces this dictionary:

2014-09-25 20:26:57.747 ParseAddress[56154:60b] {
    City = "Beverly Hills";
    State = CA;
    Street = "347 N Canon Dr";
    ZIP = 90210;
}

the possible keys for which are listed in the docs.

Upvotes: 5

Related Questions