I'm trying to display multiple locations in MKMapItem
. I am getting those locations from a CLGeocoder
, unfortunately it only accepts one location. Even though I pass in an NSArray
it just returns one location.
The following works fine with a single location, but not with multiple locations. How can I geocode multiple locations?
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
NSArray *addresses = @[@"Mumbai",@"Delhi","Banglore"];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@[addresses] completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *geocodedPlacemark = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:geocodedPlacemark.location.coordinate addressDictionary:geocodedPlacemark.addressDictionary];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:geocodedPlacemark.name];
[MKMapItem openMapsWithItems:@[mapItem] launchOptions:nil];
}];
}
For contemporary Swift readers,
async
-await
greatly simplifies the process:Swift concurrency handles dependencies between asynchronous tasks far more elegantly than the old
NSOperation
approach we had to do in Objective-C.Or, if searching on a map, perhaps
MKLocalSearch
:Needless to say, as noted above, the whole idea of multiple geocoding requests is an anti-pattern, explicitly discouraged in the
CLGeocoder
documentation.