我正在努力学习MapKit
并添加一些 MKPolyLine
作为覆盖。几个问题:
MKPolyLine
之间有什么区别?和MKPolyLineView
.什么时候用哪个?对于
MKPolyLine
init 方法的参数之一是MKMapPoint
的泛型类型(UnsafePointer
) ?不太确定那是什么意思。查看各种 SO 问题,似乎我们应该传递CLLocationCoordinate2D
的内存地址。结构作为参数,但它对我不起作用。let testline = MKPolyline() let coords1 = CLLocationCoordinate2D(latitude: 52.167894, longitude: 17.077399) let coords2 = CLLocationCoordinate2D(latitude: 52.168776, longitude: 17.081326) let coords3 = CLLocationCoordinate2D(latitude: 52.167921, longitude: 17.083730) let testcoords:[CLLocationCoordinate2D] = [coords1,coords2,coords3] let line = MKPolyline.init(points: &testcoords, count: testcoords.count) mapView.add(testline)
我不断收到 "& is not allowed passing array value as 'UnsafePointer<MKMapPoint>" argument"
.
这里有什么问题吗?
最佳答案
1.
MKPolyLine
是一个包含多个 map 坐标的类,用于定义多段线的形状,非常接近于一个坐标数组。
MKPolyLineView
是管理 MKPolyLine
的可视化表示的 View 类.如 Kane Cheshire's answer 中所述, 它已经过时了,你应该使用 MKPolyLineRenderer
.
什么时候应该使用哪个?
您需要同时使用 MKPolyLine
和 MKPolyLineRenderer
如下面的代码所示。
2.
MKPolyLine
有两个初始化器:
当你想通过[CLLocationCoordinate2D]
至 MKPolyLine.init
, 你需要使用 init(coordinates:count:)
.
(或者您可以创建一个 MKMapPoint
数组并将其传递给 init(points:count:)
。)
当你想将一个不可变数组(用 let
声明)传递给 UnsafePointer
时(非可变),你不需要前缀 &
.
下面的代码实际上是用 Xcode 9 beta 3 构建和测试的:
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let coords1 = CLLocationCoordinate2D(latitude: 52.167894, longitude: 17.077399)
let coords2 = CLLocationCoordinate2D(latitude: 52.168776, longitude: 17.081326)
let coords3 = CLLocationCoordinate2D(latitude: 52.167921, longitude: 17.083730)
let testcoords:[CLLocationCoordinate2D] = [coords1,coords2,coords3]
let testline = MKPolyline(coordinates: testcoords, count: testcoords.count)
//Add `MKPolyLine` as an overlay.
mapView.add(testline)
mapView.delegate = self
mapView.centerCoordinate = coords2
mapView.region = MKCoordinateRegion(center: coords2, span: MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02))
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
//Return an `MKPolylineRenderer` for the `MKPolyline` in the `MKMapViewDelegate`s method
if let polyline = overlay as? MKPolyline {
let testlineRenderer = MKPolylineRenderer(polyline: polyline)
testlineRenderer.strokeColor = .blue
testlineRenderer.lineWidth = 2.0
return testlineRenderer
}
fatalError("Something wrong...")
//return MKOverlayRenderer()
}
}
关于swift - MKPolyLine swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066009/