Kostenko
Kostenko

Reputation: 307

MKdirections Plotting route between 2 given points

I m using this tutorial to make a sample app. It uses a table view populated with a JSon file that contains locations. In the detail view, it uses a Map and puts a pin for the location selected in the table list view.

My question is how can I plot the route between the current users location as a starting point and the "locations" location as destination?

I now have 2 pins on my map : 1) Current location and 2)Destination but i don't know how to link them with a route. Opening the default map application with these 2 as arguments is not an option.

Thanks in advance for every answer.

Upvotes: 1

Views: 4529

Answers (1)

Sujith Thankachan
Sujith Thankachan

Reputation: 3506

Use the following code:

     MKPlacemark *source = [[MKPlacemark   alloc]initWithCoordinate:CLLocationCoordinate2DMake(sourceLatitude, sourceLongitude)   addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];
     MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
    [srcMapItem setName:@""];

    MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(destinationLatitude, destinationLongitude) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

    MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
    [distMapItem setName:@""];

    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    [request setSource:srcMapItem];
    [request setDestination:distMapItem];
    [request setTransportType:MKDirectionsTransportTypeWalking];

    MKDirections *direction = [[MKDirections alloc]initWithRequest:request];

    [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {

        NSLog(@"response = %@",response);
        NSArray *arrRoutes = [response routes];
        [arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

            MKRoute *rout = obj;

            MKPolyline *line = [rout polyline];
            [self.mkMapView addOverlay:line];
            NSLog(@"Rout Name : %@",rout.name);
            NSLog(@"Total Distance (in Meters) :%f",rout.distance);

            NSArray *steps = [rout steps];

            NSLog(@"Total Steps : %d",[steps count]);

            [steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSLog(@"Rout Instruction : %@",[obj instructions]);
                NSLog(@"Rout Distance : %f",[obj distance]);
            }];
        }];
    }];

For more information you can check apple's documentation.

Upvotes: 9

Related Questions