Search code examples
objective-cmkmapviewcore-locationpolyline

How to draw Polyline based on route in Mkmapview


Hi all I need to display Polyline in MKapview. I have done that but I need to show Polyline based on route. I'm getting like below image if am using location did update then it comes good i am try to store latitude and longitude then next time i have to displayed previous Polyline in that time i am not getting, please help me

enter image description here


Solution

  • - (void)drowRoautLines_FromLocation:(CLLocationCoordinate2D)FromLocation ToLocation:(CLLocationCoordinate2D)ToLocation
    {
        MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:FromLocation
                                                   addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil]];
        MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
        [srcMapItem setName:@"Source"];
    
        MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:ToLocation
                                                        addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil]];
        MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
        [distMapItem setName:@"Destination"];
    
        MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
        [request setSource:srcMapItem];
        [request setDestination:distMapItem];
        [request setTransportType:MKDirectionsTransportTypeAutomobile];
    
        MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
    
        [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error)
        {
            [self ShowLoading:NO];
    
            NSLog(@"response = %@",response);
            NSLog(@"error = %@",error);
            NSArray *arrRoutes = [response routes];
            if (arrRoutes.count == 0)
            {
                //Show Error Message.
            }
            else
            {
                [arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                {
    
                    MKRoute *rout = obj;
                    MKPolyline *line = [rout polyline];
                    [mapView addOverlay:line];
    
                    NSLog(@"Rout Name : %@",rout.name);
                    NSLog(@"Total Distance (in Meters) :%f",rout.distance);
                    NSArray *steps = [rout steps];
                    NSLog(@"Total Steps : %lu",(unsigned long)[steps count]);
    
                    [steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                    {
                        //NSLog(@"Rout Instruction : %@",[obj instructions]);
                    }];
                }];
            }
        }];
    
    }