Rakesh Mohan
Rakesh Mohan

Reputation: 609

How to draw line between two annotations in map view swift ios?

let latitude = NSUserDefaults.standardUserDefaults().doubleForKey(klat)
let longitude = NSUserDefaults.standardUserDefaults().doubleForKey(klong)

let location = CLLocationCoordinate2DMake(latitude, longitude)

// Second Location lat and long
let latitudeSec: CLLocationDegrees = 10.0100
let longitudeSec: CLLocationDegrees = 76.3620

let locationSec = CLLocationCoordinate2DMake(latitudeSec, longitudeSec)
let span = MKCoordinateSpanMake(1, 1)
let region = MKCoordinateRegionMake(location, span)

mapView.setRegion(region, animated: true)

I have two locations(lat and long) with two annotations. I need to know how to draw the line between these two annonations on MKMap?

Upvotes: 0

Views: 2789

Answers (1)

hoss24
hoss24

Reputation: 556

Create an array of [CLLocationCoordinate2D], convert to MKPolyline and add to map.

If you have a CLLocation could get CLLocationCoordinate2D from CLLocation.coordinate

In your case...

let pointArry = [location, locationSec]  
let myPolyline = MKPolyline(coordinates: pointArray, count: pointArray.count)
mapView.addOverlay(myPolyline)

//MARK:  MKMapViewDelegate Method (make sure class has been set as delegate)
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay.isKind(of: MKPolyline.self) {
        // draw the track
        let polyLine = overlay
        let polyLineRenderer = MKPolylineRenderer(overlay: polyLine)
        polyLineRenderer.strokeColor = UIColor.blue
        polyLineRenderer.lineWidth = 2.0
        
        return polyLineRenderer
    }
    
    return MKPolylineRenderer()
}

Upvotes: 1

Related Questions