Method one instance method
- (void)geocodeFromAddress:(NSString *)address { //6 CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) { if([placemarks count]) { CLPlacemark *placemark = [placemarks objectAtIndex:0]; CLLocation *location = placemark.location; CLLocationCoordinate2D coordinate = location.coordinate; NSLog(@"coordinate = (%f, %f)", coordinate.latitude, coordinate.longitude); } else { NSLog(@"error"); } }]; }
Method two class method this is google api
+(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr { double latitude = 0, longitude = 0; NSString *esc_addr = [addressStr 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; }