ios - 如何在 MKMapView 上用不同的笔画/颜色绘制 2 条 MKPolyline?

标签 ios mapkit mkmapview swift4

我有一个 MKMapView,我在其中跟踪用户的路径(它是一个正在运行的应用程序),但要求是创建一条具有两种颜色的线。一个用于笔划的中心,另一个用于笔划的边界。为此,我实现了 UIViewController 类的 func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer 方法,以返回渲染器。

我使用的是 Swift 4

有什么想法吗?

提前致谢。

最佳答案

好吧,我在写问题的时候就找到了解决方案,所以我会告诉你解决方案。

首先,您必须创建两个扩展 MKPolyline 类的类

fileprivate class ForegroundOverlay: MKPolyline{

}
fileprivate class BackgroundOverlay: MKPolyline{

}

其次,您必须修改位置更新时触发的事件

    var positions = [CLLocationCoordinate2D]()
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation

        positions.append(userLocation.coordinate)

        print("Nuber of locations \(positions.count)")
        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")

        speedIndicator.text = "Speed: \(userLocation.speed * 3.6). Altitude: \(userLocation.altitude)"


        let fPolyLine = BackgroundOverlay(coordinates: positions, count: positions.count)

        mapView.addOverlays([fPolyLine], level: MKOverlayLevel.aboveRoads)

        let bPolyLine = ForegroundOverlay(coordinates: positions, count: positions.count)

        mapView.addOverlays([bPolyLine], level: MKOverlayLevel.aboveRoads)

    }

第三,您必须询问折线是一个类还是另一个类。

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    if overlay is ForegroundOverlay {
        renderer.strokeColor = UIColor(red: 230/255, green: 230/255, blue: 1, alpha: 0.5)
        renderer.lineWidth = 10
    } else {
        renderer.strokeColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.5)
        renderer.lineWidth = 30
    }

    return renderer
}

结果将如下所示

enter image description here

关于ios - 如何在 MKMapView 上用不同的笔画/颜色绘制 2 条 MKPolyline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878313/

相关文章:

ios - 使用ForEach循环和Picker的SwiftUI意外索引

IOS5 __block 变量在范围外抛出 EXC_BAD_ACCESS

ios - 如何获取支持iOS 9的init(coordinates)的较早语法?

iphone - 如何给MKMapView异步添加注解?

c++ - 如何计算每分钟 MP4 文件(MPEG4,H.264)的大小?

iphone - 如何在 iOS 上跨设备识别用户?

ios - 使用 AVPlayer 音频播放 AVMutableComposition 不同步

ios - 如何在苹果 map 上加载JSON数据以放置标记IOS

iphone - 注释在 iOS 9 中变为默认状态

ios - MKMapView 内存管理