4

I want to show a route on a MKMapView between the current location and a desired location as an annotation.

What is the best way to do this?

Onato
  • 9,916
  • 5
  • 46
  • 54
1337code
  • 93
  • 1
  • 2
  • 7
  • possible duplicate of [drawing routes on MKMapView](http://stackoverflow.com/questions/5018826/drawing-routes-on-mkmapview) – Alex Terente Dec 22 '11 at 14:46

3 Answers3

8

///in .h add delegate MKMapViewDelegate

///in .m file

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation     *)newLocation fromLocation:(CLLocation *)oldLocation
{

     CLLocationCoordinate2D newcordinate =   newLocation.coordinate;
     CLLocationCoordinate2D oldcordinate =   oldLocation.coordinate;

       MKMapPoint * pointsArray =
               malloc(sizeof(CLLocationCoordinate2D)*2);

           pointsArray[0]= MKMapPointForCoordinate(oldcordinate); 
           pointsArray[1]= MKMapPointForCoordinate(newcordinate);    

            MKPolyline *  routeLine = [MKPolyline polylineWithPoints:pointsArray count:2];
           free(pointsArray);

            [MapView addOverlay:routeLine];  //MkMapView declared in .h
}

//MKMapViewDelegate

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKOverlayView* overlayView = nil;


          MKPolylineView  * _routeLineView = [[[MKPolylineView alloc]                   initWithPolyline:self.routeLine] autorelease];
            _routeLineView.fillColor = self.PathColor;
           _routeLineView.strokeColor = self.PathColor;
          _routeLineView.lineWidth = 15;
            _routeLineView.lineCap = kCGLineCapSquare;


            overlayView = _routeLineView;

            return overlayView;

}
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
Andrew
  • 168
  • 5
2

I have try following code...it works very well in my project...try it..

First download KMLParser.h and KMLParser.m from this link:-

Also download DDAnnotation.h and DDAnnotation.m file from this link:-

Now Create a View Controller Like SomeViewController.

Add following library:-

  1. CoreLocation.framework
  2. MapKit.framework
  3. QuartzCore.framework

In SomeViewController.h import KMLParser.h file.

Write following code in SomeViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "KMLParser.h"
@interface SomeViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate, MKOverlay>{

    double currentLat;
    double currentLong;

    double desiredLatitude;
    double desiredLongitude;

    MKMapView *mapView;
    KMLParser *kml;
    NSMutableArray *annotations;

} @property(nonatomic, retain)IBOutlet MKMapView *mapView;

@end

Now in the SomeViewController.xib drag and drop the MapView and give link it with mapView from File's Owner. Also set delegate of MapView to File's owner.

Now in SomeViewController Write the following code:-

#import "SomeViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "DDAnnotation.h"

@implementation SomeViewController
@synthesize mapView;

- (void)viewDidLoad {
    [super viewDidLoad];

    currentLat = 21.215538; //You can set current latitude here. 
    currentLong = 72.858753; //You can set current longitude here.

    desiredLatitude = 21.211976; //You can set destination latitude here.
    desiredLongitude = 72.851593; //You can set destination longitude here.

    MKCoordinateRegion region = {{0.0f, 0.0f}, {100.0f, 100.0f}};
    CLLocation* currentLocation = [[CLLocation alloc] initWithLatitude:currentLat longitude:currentLong];
    region.center = currentLocation.coordinate;
    region.span.longitudeDelta = 0.05;
    region.span.latitudeDelta  = 0.05;

    [self.mapView setRegion:region animated:YES];

    annotations=[[NSMutableArray alloc] init];

    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = currentLat;
    theCoordinate.longitude = currentLong;

    DDAnnotation* myAnnotation=[[DDAnnotation alloc] init];

    myAnnotation.coordinate=theCoordinate;
    myAnnotation.title=@"You are here";
    myAnnotation.subtitle=@"Current location";

    [mapView addAnnotation:myAnnotation];
    [annotations addObject:myAnnotation];

    CLLocationCoordinate2D theCoordinate1;
    theCoordinate1.latitude = desiredLatitude;
    theCoordinate1.longitude = desiredLongitude;

    DDAnnotation* myAnnotation1=[[DDAnnotation alloc] init];

    myAnnotation1.coordinate=theCoordinate1;
    myAnnotation1.title=@"Desired Location's Title";
    myAnnotation1.subtitle= @"Desired Location's Sub-title";

    [mapView addAnnotation:myAnnotation1];
    [annotations addObject:myAnnotation1];

    NSString *path = [NSString stringWithFormat:@"http://maps.google.com/maps?f=d&hl=en&saddr=%f,%f&daddr=%f,%f&ie=UTF8&0&om=0&output=kml",currentLat,currentLong,desiredLatitude,desiredLongitude];
    NSLog(@" Path String : %@", path); 
    kml = [[KMLParser alloc] initWithURL:[NSURL URLWithString:path]];
    [kml parseKML];

    // Add all of the MKOverlay objects parsed from the KML file to the map.
    NSArray *overlays = [kml overlays];
    [self.mapView addOverlays:overlays];

}


#pragma mark MKMapViewDelegate

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    return [kml viewForOverlay:overlay];
}

- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation{

    // if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]]){
        return nil;
    }
    else{

        static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
        MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
                                         initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
        pinView.animatesDrop=YES;
        pinView.canShowCallout=YES;
        pinView.pinColor=MKPinAnnotationColorGreen;


        return pinView;
    }   
}
Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
Sunil Zalavadiya
  • 1,993
  • 25
  • 36
  • Not working giving sigabrt at method kml = [[KMLParser parseKMLAtURL:[....]; giving warning as foundClass method '+parseKMLAtURL:' not found (return type defaults to 'id') – The iCoder Jun 13 '12 at 14:09
  • Have you added KMLParser.h and KMLParser.m class file from following link to your project? http://developer.apple.com/library/ios/#samplecode/KMLViewer/Listings/Classes_KMLParser_m.html#//apple_ref/doc/uid/DTS40010046-Classes_KMLParser_m-DontLinkElementID_4 – Sunil Zalavadiya Jun 13 '12 at 15:54
  • Yes the method has changed in KMLParser class file. Use -(id)initWithURL:(NSURL *)url; with - (void)parseKML method instead of "parseKMLAtURL:" – Sunil Zalavadiya Jun 14 '12 at 09:05
  • Also i have edited above code with new code. you can check now. – Sunil Zalavadiya Jun 14 '12 at 09:10
  • NSLog("%@", overlays); is empty – nr5 Dec 15 '12 at 05:02
0

You have to compute your self the way points and draw the route as a layer. The is no public api to show route in a MKMapView.

The fastest solution is to open maps app of the phone with the route.

Alex Terente
  • 12,006
  • 5
  • 51
  • 71
  • Yes, I know for that, but I've seen in some apps taht it is possible to draw a route between two locations, just don't know how, I don't need directions to here feature, for that the app will launch Maps app, I just want map to draw a route on map, and I can't find anywhere how to to that but it's possible – 1337code Dec 22 '11 at 13:45