Reputation: 11
Xcode 11.1, Swift 4
How to draw a line between three locations (points) using Mapkit in Swift?
let london = Capital(title: "London", coordinate: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), info: "Home to the 2012 Summer Olympics.")
let oslo = Capital(title: "Oslo", coordinate: CLLocationCoordinate2D(latitude: 59.95, longitude: 10.75), info: "Founded over a thousand years ago.")
Thanks
Upvotes: 1
Views: 823
Reputation: 146
To connect any number of points you can use MKPolyline
and its MKPolylineRenderer
view. First you add the overlay to your map, then provide the view with visual settings for the polyline in the delegate method:
import UIKit
import MapKit
struct Capital {
let title: String
let coordinate: CLLocationCoordinate2D
let info: String
}
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let london = Capital(title: "London", coordinate: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), info: "Home to the 2012 Summer Olympics.")
let oslo = Capital(title: "Oslo", coordinate: CLLocationCoordinate2D(latitude: 59.95, longitude: 10.75), info: "Founded over a thousand years ago.")
mapView.addOverlay(MKPolyline(coordinates: [london.coordinate, oslo.coordinate], count: 2))
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polylineRenderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
polylineRenderer.strokeColor = UIColor.black
polylineRenderer.lineWidth = 4.0
return polylineRenderer
}
}
Here is the result of the code above:
Upvotes: 5