先來看看 MKGeodesicPolyline 在 Apple Developer Documentation 上的介紹: A line-based shape that follows the contours of the Earth to create the shortest path between the specified points.
繪製 Polyline
首先我們在建置 MKGeodesicPolyline 的時候, 給予它一個 [CLLocationCoordinate2D],並宣告要繪製幾個點; 接著讓 MKMapView 新增進去。
let geodesicPolyline = MKGeodesicPolyline.init(coordinates: [start, end], count: 2)
mapView.add(geodesicPolyline)
再來我們需要透過 MKMapViewDelegate 的 function 來定義 MKGeodesicPolyline 的 UI:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
guard let polyline = overlay as? MKPolyline else {
return MKOverlayRenderer(overlay: overlay)
}
let renderer = MKPolylineRenderer.init(polyline: polyline)
renderer.lineWidth = 1
renderer.strokeColor = .red
return renderer
}
取得 Polyline 中間的經緯度
MKGeodesicPolyline 的繪製是由很多個點所連起來的, 可以利用 points() -> UnsafeMutablePointer 來取得。
@available(iOS 4.0, *)
open class MKMultiPoint : MKShape {
open func points() -> UnsafeMutablePointer<MKMapPoint>
open var pointCount: Int { get }
// Unproject and copy points into the provided array of coordinates that
// must be large enough to hold range.length coordinates.
open func getCoordinates(_ coords: UnsafeMutablePointer<CLLocationCoordinate2D>, range: NSRange)
}
我們可以透過 pointCount 來得知有幾個點, 接著決定要使用哪個點的位置;
MKCoordinateForMapPoint(polyline.points()[index])