In ios when we want to show a route or poly line between two coordinate then we use the following function.
most of time we use this when we want to dislplay the route from current location to destination address.
Here mapView is the property of your MKmap view and routeLine is property of MKPolyline.
#import <MapKit/MapKit.h>
- (void)viewWillAppear:(BOOL)animated {
_mapView.delegate=self;
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 37.33259552;
zoomLocation.longitude= -122.03031802;
MapAnnotation *newAnnotation = [[MapAnnotation alloc]
initWithTitle:@"Title1" andCoordinate:zoomLocation];
[mapView addAnnotation:newAnnotation];
CLLocationCoordinate2D location2;
location2.latitude = (double) 37.35239;
location2.longitude = (double) -122.025919;
MapAnnotation *newAnnotation2 = [[MapAnnotation alloc]
initWithTitle:@"Title2" andCoordinate:location2];
[mapView addAnnotation:newAnnotation2];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*OFFSETZOOM, 0.5*OFFSETZOOM);
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(zoomLocation.latitude, zoomLocation.longitude) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(location2.latitude, location2.longitude) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];
MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeWalking];
MKDirections *directions =
[[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:
^(MKDirectionsResponse *response, NSError *error) {
if (error) {
// Handle error
} else {
[self showRoute:response];
}
}];
//[self.mapView addOverlay:self.routeLine];
[mapView setRegion:viewRegion animated:YES];
}
-(void)showRoute:(MKDirectionsResponse *)response
{
for (MKRoute *route in response.routes)
{
[mapView addOverlay:route.polyline level:MKOverlayLevelAboveLabels];
for (MKRouteStep *step in route.steps)
{
NSLog(@"%@", step.instructions);
}
}
}
#pragma MKMap View
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay {
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
renderer.strokeColor = [UIColor orangeColor];
renderer.lineWidth = 6.0;
return renderer;
}
0 Comment(s)