Similar to the post about reverse geocoding, the forward geocoded uses CLGeocoder.
I wrote a quick static method that takes an address string (e.g., “4700 Louisiana 22 #1, Mandeville, LA 70471”) and a completion handler. All this method does is create the CLGeocoder for you and make the call.
It’s mostly just a way to keep the code contained…
+(void)forwardGeocode:(NSString*)addressString
completionHandler:(void (^)(NSArray *placemarks, NSError *error))completionHandler;
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:addressString
completionHandler:completionHandler];
}
If you’re going to call this a lot, you can make the geocoder a static variable so it’s not created each time.
So to call this method, assuming it’s in a class called Constants, you’d call it w/ the address and a completion handler…
-(void)forwardGeocode:(NSString*)addressString;
{
addrPlacemark = nil;
[Constants forwardGeocode:addressString
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error)
NSLog(@"Geocode error: %@", error);
else if (placemarks.count > 0)
{
addrPlacemark = [placemarks firstObject];
NSLog(@"fwd geocode: %f %f",
addrPlacemark.location.coordinate.latitude,
addrPlacemark.location.coordinate.longitude);
}
}];
}
I’m using addrPlacemark as an instance variable to store the value. I nil it out to start and then call our help method above passing in the address string and completion handler.
I handle the error OR get the first object and log out the lat/lng.
If you used the code from the reverse geocoding post, you could send in the result of the reverse geocoding into this method and test a round trip.
