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; }
For Swift:
ReplyDeletefunc convertLatLongToAddress convert (latitude:Double,longitude:Double){
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// Location name
if let locationName = placeMark.location {
print(locationName)
}
// Street address
if let street = placeMark.thoroughfare {
print(street)
}
// City
if let city = placeMark.subAdministrativeArea {
print(city)
}
// Zip code
if let zip = placeMark.isoCountryCode {
print(zip)
}
// Country
if let country = placeMark.country {
print(country)
}
})
}