Skip to content

Instantly share code, notes, and snippets.

@joelmarquez90
Created January 8, 2015 14:35
Show Gist options
  • Save joelmarquez90/5bc26b6a5fdf754bfbe6 to your computer and use it in GitHub Desktop.
Save joelmarquez90/5bc26b6a5fdf754bfbe6 to your computer and use it in GitHub Desktop.
Calculate and draw multiple routes on a map
- (IBAction)btnDirectionsPressed:(id)sender {
[self enableUI:NO]; // This method enables or disables all the UI elements that interact with the user
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); // Create the semaphore
__block NSMutableArray *routes = [[NSMutableArray alloc] init]; // Arrays to store MKRoute objects and MKAnnotationPoint objects, so then we can draw them on the map
__block NSMutableArray *annotations = [[NSMutableArray alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
for (RouteObject *routeObject in _locations) {
MKDirectionsRequest *directionsRequest = [MKDirectionsRequest new];
[directionsRequest setTransportType:MKDirectionsTransportTypeAutomobile];
[directionsRequest setSource:[routeObject originMapItem]];
[directionsRequest setDestination:[routeObject destinationMapItem]];
[directionsRequest setRequestsAlternateRoutes:NO];
MKDirections *direction = [[MKDirections alloc] initWithRequest:directionsRequest];
// For each object in the locations array, we request that route from its origin and its destination
[direction calculateDirectionsWithCompletionHandler: ^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(@"There was an error getting your directions");
return;
}
MKRoute *route = [response.routes firstObject];
[routes addObject:route];
[annotations addObject:[routeObject destinationAnnotation]];
dispatch_semaphore_signal(semaphore); // Send the signal that one semaphore is ready to consume
}];
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
for (int i = 0; i < _locations.count; i++) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // Wait until one semaphore is ready to consume
dispatch_async(dispatch_get_main_queue(), ^{ // For each element, dispatch to the main queue to draw route and annotation corresponding to that location
MKRoute *route = routes[i];
[self.mapView addOverlay:route.polyline];
[self.mapView addAnnotation:annotations[i]];
});
}
dispatch_async(dispatch_get_main_queue(), ^{ // Finally, dispatch to the main queue enabling elements and resizing map to show all the annotations
[self enableUI:YES];
[self fitRegionToRoutes];
});
});
}
@canaksoy
Copy link

canaksoy commented Jun 4, 2016

code for RouteObject?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment