Get latitude/longitude from address

Luka picture Luka · Oct 1, 2009 · Viewed 35.1k times · Source

How can I get latitude and longitude from a full address (street, city, etc.) input by the user, using the iPhone SDK 3.x?

Answer

Thomas Tempelmann picture Thomas Tempelmann · Jun 9, 2010

Here's an updated, more compact, version of unforgiven's code, which uses the latest v3 API:

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    return center;
}

It makes the assumption that the coordinates for "location" come first, e.g. before those for "viewport", because it just takes the first coords it finds under the "lng" and "lat" keys. Feel free to use a proper JSON scanner (e.g. SBJSON) if you are worried about this simple scanning technique used here.