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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…