How to draw route between two locations and plot main points also using MapKit?

11,706

Solution 1

The question has been asked several times. I guess you are taking code from http://iosguy.com/2012/05/22/tracing-routes-with-mapkit/ You can also look at that SO question: Plotting Route with Multiple Points in iOS

You can get the code from http://iosboilerplate.com too and contribute to it.

And last but not least, there's a framework out there that can help you do it for a small sum of money (but nothing compared to what it would take you to do same): http://www.cocoacontrols.com/controls/mtdirectionskit

Solution 2

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>


@interface ViewController : UIViewController<MKMapViewDelegate>
{
    NSData *alldata;
    NSMutableDictionary *data1;

    NSMutableArray *RouteLocation;
    NSMutableArray *RouteName;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapview;
@property (nonatomic, retain) MKPolyline *routeLine;
@property (nonatomic, retain) MKPolylineView *routeLineView;

-(void)LoadMapRoute;
@end



#import "ViewController.h"



@implementation ViewController
@synthesize mapview,routeLine,routeLineView;

- (void)viewDidLoad {
    [super viewDidLoad];
     self.mapview.delegate = self;
    // Do any additional setup after loading the view, typically from a nib.
    RouteName = [[NSMutableArray alloc] initWithObjects:@"Ahmedabad",@"Rajkot", nil];
    RouteLocation = [[NSMutableArray alloc] initWithObjects:@"23.0300,72.5800",@"22.3000,70.7833", nil];
    [self LoadMapRoute];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//-------------------------------------
// ************* Map ******************
//-------------------------------------

-(void)LoadMapRoute
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.8, 0.8);
    MKCoordinateRegion region;
    region.span = span;
    region.center= CLLocationCoordinate2DMake(23.0300,72.5800);


    // Distance between two address
    NSArray *coor1=[[RouteLocation objectAtIndex:0] componentsSeparatedByString:@","];
    CLLocation *locA = [[CLLocation alloc] initWithLatitude:[[coor1 objectAtIndex:0] doubleValue] longitude:[[coor1 objectAtIndex:1] doubleValue]];

    NSArray *coor2=[[RouteLocation objectAtIndex:1] componentsSeparatedByString:@","];
    CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[coor2 objectAtIndex:0] doubleValue] longitude:[[coor2 objectAtIndex:1] doubleValue]];
    CLLocationDistance distance = [locA distanceFromLocation:locB];
    NSLog(@"Distance :%.0f Meters",distance);


    NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", [RouteLocation objectAtIndex:0],[RouteLocation objectAtIndex:1] ];

    NSURL *url = [NSURL URLWithString:baseUrl];
    alldata = [[NSData alloc] initWithContentsOfURL:url];

    NSError *err;
    data1 =[NSJSONSerialization JSONObjectWithData:alldata options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&err];

    NSString *overviewPolyline = [[[[data1 objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
    NSArray *path = [self decodePolyLine:overviewPolyline];



    if (err)
    {
        NSLog(@" %@",[err localizedDescription]);
    }



    NSInteger numberOfSteps = path.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++) {
        CLLocation *location = [path objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;

        coordinates[index] = coordinate;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
    [self.mapview addOverlay:polyLine];


//    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:path count: path.count];
//    [self.mapview addOverlay:polyLine];
//    [self.mapview setRegion:region animated:YES];
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor colorWithRed:204/255. green:45/255. blue:70/255. alpha:1.0];
    polylineView.lineWidth = 5;

    return polylineView;
}


-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len) {
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
        printf("[%f,", [latitude doubleValue]);
        printf("%f]", [longitude doubleValue]);
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
        [array addObject:loc];
    }

    return array;
}
@end
Share:
11,706
Prince Kumar Sharma
Author by

Prince Kumar Sharma

Ambition to get extreme knowledge in my field.

Updated on June 05, 2022

Comments

  • Prince Kumar Sharma
    Prince Kumar Sharma almost 2 years

    I am using MapKit api to get current location on map and drawing route between two location pointed by drop pins.I also want to get all the main stands between its route. I m using below function to get route between two location

    - (NSArray*)getRoutePointFrom:(MyLocation*)origin to:(MyLocation*)destination
    {
     NSString* saddr = [NSString stringWithFormat:@"%f,%f", origin.coordinate.latitude, origin.coordinate.longitude];
     NSString* daddr = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];
    
    
     NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false&avoid=highways&mode=driving",saddr,daddr]];
    
     NSError *error=nil;
    
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    
     [request setURL:url];
     [request setHTTPMethod:@"POST"];
    
      NSURLResponse *response = nil;
    
      NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: &error];
    
      NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
     SBJsonParser *json=[[SBJsonParser alloc] init];
    
     NSDictionary *dic=[json objectWithString:responseString error:nil];
    
     NSDictionary *nextdic=[dic valueForKey:@"routes"];
     NSDictionary *legdic=[nextdic valueForKey:@"legs"];
     NSDictionary *stepdic=[legdic valueForKey:@"steps"];
    
     NSArray *array=[[NSArray alloc] initWithArray:[[stepdic valueForKey:@"polyline"] valueForKey:@"points"]];  
    
    
     NSString *string=[NSString stringWithFormat:@"%@",[[array objectAtIndex:0] objectAtIndex:0]];
    
    
    
    
     return [self decodePolyLine:[string mutableCopy]];
    
    }
    
    
    
    -(NSMutableArray *)decodePolyLine:(NSString *)encodedStr 
    {  
    
     NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];  
     [encoded appendString:encodedStr];  
     [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"  
                                 options:NSLiteralSearch  
                                   range:NSMakeRange(0, [encoded length])];  
     NSInteger len = [encoded length];  
    
     NSInteger index = 0;  
     NSMutableArray *array = [[NSMutableArray alloc] init] ;  
     NSInteger lat=0;  
     NSInteger lng=0;  
     while (index < len) {  
      NSInteger b;  
      NSInteger shift = 0;  
      NSInteger result = 0;  
      do {  
       b = [encoded characterAtIndex:index++] - 63;  
       result |= (b & 0x1f) << shift;  
       shift += 5;  
      } while (b >= 0x20);  
      NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));  
      lat += dlat;  
      shift = 0;  
      result = 0;  
      do {  
       b = [encoded characterAtIndex:index++] - 63;  
       result |= (b & 0x1f) << shift;  
       shift += 5;  
      } while (b >= 0x20);  
      NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));  
      lng += dlng;  
      NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];  
      NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];  
      //          printf("[%f,", [latitude doubleValue]);  
      //          printf("%f]", [longitude doubleValue]);  
      CLLocation *loc =[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;  
      [array addObject:loc];  
     }  
    
     NSLog(@"array in decode polygon is %@",array);
    
     return array;  
    }
    

    but it is not working . ..

    help regarding this thank you!...

  • Moxarth
    Moxarth almost 7 years
    is there any other way of showing route without using google api ?