I have been working on MapView on how to show routes etc etc. I have used long press gesture to drop a pin and a polyline is shown between the two pins dropped via long press. Now the polyline which connects the two pins is a straight line, i want to render is properly according to the route on the map. Plz help me. Heres the code
MapView.h
-(void)viewDidLoad {
[super viewDidLoad];
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(addPin:)];
recognizer.minimumPressDuration = 0.5;
[self.mapView2 addGestureRecognizer:recognizer];
}
-(void)addPin:(UIGestureRecognizer *)recognizer {
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
// convert touched position to map coordinate
CGPoint userTouch = [recognizer locationInView:self.mapView2];
CLLocationCoordinate2D mapPoint = [self.mapView2 convertPoint:userTouch toCoordinateFromView:self.mapView2];
NSLog(@"Touched Coord :- %f", mapPoint);
Pin *newPin = [[Pin alloc]initWithCoordinate:mapPoint]; //PIN is NSOBJECT
newPin.title = @"source";
[self.mapView2 addAnnotation:newPin];
[self.allPins addObject:newPin];
[self drawLines:self];
}
- (IBAction)drawLines:(id)sender {
[self drawLineSubroutine];
[self drawLineSubroutine];
}
-(IBAction)undoLastPin:(id)sender {
// grab the last Pin and remove it from our map view
Pin *latestPin = [self.allPins lastObject];
[self.mapView2 removeAnnotation:latestPin];
[self.allPins removeLastObject];
// redraw the polyline
[self drawLines:self];
}
-(void)drawLineSubroutine {
// remove polyline if one exists
[self.mapView2 removeOverlay:self.polyline];
// create an array of coordinates from allPins
CLLocationCoordinate2D coordinates[self.allPins.count];
int i = 0;
for (Pin *currentPin in self.allPins) {
coordinates[i] = currentPin.coordinate;
i++;
}
// create a polyline with all cooridnates
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinates count:self.allPins.count];
[self.mapView2 addOverlay:polyline];
self.polyline = polyline;
// create an MKPolylineView and add it to the map view
self.lineView = [[MKPolylineView alloc]initWithPolyline:self.polyline];
self.lineView.strokeColor = [[UIColor blueColor]colorWithAlphaComponent:0.5];
self.lineView.lineWidth = 7;
// for a laugh: how many polylines are we drawing here?
self.title = [[NSString alloc]initWithFormat:@"%lu", (unsigned long)self.mapView2.overlays.count];
}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {
return self.lineView;
}