I am trying to do a forward geocode on a string, and it usually works ok, but for some locations, like "Vancouver" it returns null for the locality of the resulting placemark, but it does return the country, province, and coordinates. I even tried reverse geocoding the coordinate I found from forward geocoding, and although that didn't fail, it returned a different location, "Port Moody".
The weirdest part is that I tried running Vancouver through Apple's sample code for the Geocoder and it works just fine. The locality does not come up null.
Also, I was testing it out, and it suddenly started working, and then I checked again and it stopped working. What gives?
Here's my code. Doubt it will help much though.
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:textField.text completionHandler:^(NSArray *placemarks, NSError *error) {
self.placemark = [[MKPlacemark alloc] initWithPlacemark:[placemarks objectAtIndex:0]];
if (error) {
NSLog(@"Geocode error %@",error.debugDescription);
[self alertForFailedGeocode];
return;
}
if (self.placemark.locality == nil || self.placemark.country == nil) {
//eg if you search "Canada" you'll get a nil locality, and the coordinate is in the middle of nowhere.
if (self.placemark.location) {
[geocoder reverseGeocodeLocation:self.placemark.location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
[self alertForFailedGeocode];
return;
}
self.placemark = [placemarks objectAtIndex:0];
[self alertForConfirmGeocode:[self locationStringForPlacemark:self.placemark]];
self.location = self.placemark.location;
self.isUsingCurrentLocation = FALSE;
return;
}];
return;
}
else {
NSLog(@"Geocode failed BECAUSE nil locality or country or both");
[self alertForFailedGeocode];
return;
}
}
NSLog(@"%d places found",placemarks.count);
[self alertForConfirmGeocode:[self locationStringForPlacemark:self.placemark]];
self.location = self.placemark.location;
self.isUsingCurrentLocation = FALSE;
}];
return YES;
}
The Geocoding operations are not handled on the device and requires internet connection as they happen on cloud. It has its pros and cons.
Pros:
Cons:
Now coming to your condition, my guess is somehow due to internet connection, you are not able to use geocoding APIs completely. May be thats why you are not getting the locality.
The question is then how are you getting the country, province, and coordinates?