gpt4 book ai didi

swift - MapKit 从坐标绘制折线 Swift 5

转载 作者:行者123 更新时间:2023-11-30 10:36:00 24 4
gpt4 key购买 nike

我有一个 CLLocationCooperative2D 数组,需要绘制一条从数组中的第一个索引到最后一个索引的线。

我已经在这里和其他地方看到了答案,但它们主要适用于旧版本的 swift,或者适用于首先转换为 double 或其他任何值的字符串数组,或者仅适用于单个位置。

我尝试创建 MKPolyline、viewForOverlay 等,但无法显示该线。我错过了什么?

let locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 3000
var locations: [CLLocationCoordinate2D] = []
var latitude: [CLLocationDegrees] = []
var longitude: [CLLocationDegrees] = []

override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.register(MKMarkerAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
createAnnotations()
centerMapOnLocation(location: initialLocation)
var polyline = MKPolyline(coordinates: &locations, count: locations.count)
mapView.addOverlay(polyline)
}
// MARK: - Create Annotaions
func createAnnotations() {
locations = zip(latitude, longitude).map(CLLocationCoordinate2D.init)
AppLogger.logInfo("\(locations)")
for location in locations {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
mapView.addAnnotation(annotation)
}
}
// MARK: - Region Zoom
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegion(center: location.coordinate,
latitudinalMeters: regionRadius,
longitudinalMeters: regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
// MARK: - Draw Polylines
func mapView(mapView: MKMapView!, viewForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if (overlay is MKPolyline) {
let pr = MKPolylineRenderer(overlay: overlay)
pr.strokeColor = UIColor.blue.withAlphaComponent(0.5)
pr.lineWidth = 5
return pr
}
return nil
}

预期输出:从位置数组中,我们基本上绘制了行驶路线。这不是获取路线的方法,因为驱动器已被占用。

最佳答案

使用 Swift 5

首先,您需要使用 CLLocationCooperative2D 数组声明 MKPolyline:

let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
mapView.addOverlay(polyline)

然后在您的 MKMapViewDelegate 上,您需要向折线添加颜色,如下例所示:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

if let routePolyline = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: routePolyline)
renderer.strokeColor = UIColor.mySpecialBlue().withAlphaComponent(0.9)
renderer.lineWidth = 7
return renderer
}

return MKOverlayRenderer()
}

通过这种方法,您将能够重新创建如下内容: Urbvan App

关于swift - MapKit 从坐标绘制折线 Swift 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58013956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com