Making use of the mapkit and core location frameworks we can easily draw a poly line indicating the direction from the given source lat,long to destination lat,long . We can set the source and the destination point coordinates and create the source and destination map items by using the below code.
//To set the source place mark MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.333144, -122.021509) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ]; //To create the source map items MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
Similarly we use same to set the destination place mark and map item using,
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.331741, -122.030333) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ]; MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
We can now get the direction between the source and destination bu making the MKDirectionRequest as shown below.
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init]; [request setSource:srcMapItem]; [request setDestination:distMapItem]; request.requestsAlternateRoutes = YES; //for alternate routes from src to destination. [request setTransportType:MKDirectionsTransportTypeAutomobile];
The response of the MKDirectionRequest contains the direction details .
MKDirections *direction = [[MKDirections alloc] initWithRequest:request]; [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) { NSLog(@"response = %@",response); //Contains the calculated direction information from source to destination. }];
Now we have the directions we make use of the below map view delegate method to draw the poly line from source to destination points on the map.
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay { if ([overlay isKindOfClass:[MKPolyline class]]) { MKPolylineView* aView = [[MKPolylineView alloc]initWithPolyline:(MKPolyline*)overlay] ; aView.strokeColor = [[UIColor colorWithRed:69.0/255.0 green:147.0/255.0 blue:240.0/255.0 alpha:1.0] colorWithAlphaComponent:1]; aView.lineWidth = 10; return aView; } returne nil; }
We can also make use of the viewForLocation: map view delegate method to change the appearance of the map pins of the source and the destination points on the map.
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotationPoint{ static NSString *annotationIdentifier = @"annotationIdentifier"; MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotationPoint reuseIdentifier:annotationIdentifier]; if ([[annotationPoint title] isEqualToString:@"Source"]) { pinView.pinColor = MKPinAnnotationColorRed; }else{ pinView.pinColor = MKPinAnnotationColorGreen; } return pinView; }
Download the sample code here: GitHub Link