简体   繁体   中英

Detect what route the user tap on map

I have a project where I show directions between current location and another location on a map (MapKit)

All works well. And I can get alternative routes.

request.requestsAlternateRoutes = YES;

But when the user tap on a route I show an annotation with distance and some other info. I want to pass this spesific route to another view. How can I achieve that? Like the original Map app on iOS. I can get different routes, and tap on a route to get direction details.

I have googled a lot, and the closest example is this:

[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {        
// Now handle the result
if (error) {
    NSLog(@"There was an error getting your directions");
    return;
}

_currentRoute = [response.routes firstObject];

But _currentRoute is the first one. I want to let the user select currentRoute on tap on the map.

I figured it out. Not so elegant, but it does the job.

  1. Make an ivar - NSMutableArray *routeArray in the header file.

I also have a MKMapView outlet in my header.

  1. In my getDirections method, I tagged the MKMapView instance with a counter and added the route object to the routeArray.

When the delegate for making the Annotation is run, I can tag the anntotationView with the mapView.tag.

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
  1. When I tap on the annotation:

    • (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control

I pass the view.tag to my segue.

    NSLog(@"Counter tag: %ld", (long)view.tag);
[self performSegueWithIdentifier:@"detaljer" sender:view];
  1. I can then pass my selected route to my new view.

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { WeatherTableViewController *routeController = [segue destinationViewController]; long row = [sender tag];

    MKRoute *route = routeArray[row]; routeController.selectedRoute = route; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM