Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How to draw line between two points on MapKit?

I have Latitude and Longitude of two points and Want to Draw line between these two points with Pin on MapKit.

I have googled but Could not find some suitable solution because the one I found was drawing overlay with array of Data points but I do not have any array of points between these two points.

Just two points and want to draw line between these two points.

Please help.

like image 807
Azhar Avatar asked May 15 '12 09:05

Azhar


People also ask

How to draw a route between two locations using MapKit in Swift?

swift file is visible. Ctrl and drag from the Map Kit View to the ViewController class to create the following Outlet. Select the Map Kit View and select the Pin icon in the lower-right corner of the Interface Builder (3rd button from the left). Select all pin directions and deselect "Constrain to margins".

How do I draw a route in Apple Maps?

In the Maps app on your Mac, click a location on the map, such as an intersection, landmark, or business. In the place card, do one of the following: Click Create Route, then enter the destination in the To field (or click the Swap Directions button , then enter the starting point in the From field).


1 Answers

First make your view controller implement the MKMapViewDelegate protocol and declare the properties you will need:

@property (nonatomic, retain) MKMapView *mapView; //this is your map view
@property (nonatomic, retain) MKPolyline *routeLine; //your line
@property (nonatomic, retain) MKPolylineView *routeLineView; //overlay view

then in viewDidLoad (for example, or wherever you initialize)

//initialize your map view and add it to your view hierarchy - **set its delegate to self***
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = CLLocationCoordinate2DMake(lat1, lon1); 
coordinateArray[1] = CLLocationCoordinate2DMake(lat2, lon2);


self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
[self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible

[self.mapView addOverlay:self.routeLine];

then implement the MKMapViewDelegate's method -(MKOverlayView *)mapView:viewForOverlay:

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if(overlay == self.routeLine)
    {
        if(nil == self.routeLineView)
        {
            self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
            self.routeLineView.fillColor = [UIColor redColor];
            self.routeLineView.strokeColor = [UIColor redColor];
            self.routeLineView.lineWidth = 5;

        }

        return self.routeLineView;
    }

    return nil;
}

You can adjust the code to fit your need, but it's pretty much straight forward for 2 or more points.

like image 87
graver Avatar answered Nov 06 '22 16:11

graver