如何在不同笔画/颜色的MKMapView上绘制2个MKPolyline?

问题描述 投票:1回答:1

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

我正在使用Swift 4

有任何想法吗?

提前致谢。

ios mapkit mkmapview swift4
1个回答
1
投票

好的,我在写这个问题时达到了解决方案,所以我会告诉你解决方案。

首先,您必须创建两个扩展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

© www.soinside.com 2019 - 2024. All rights reserved.