在Mapbox上如何绘制带边框的折线?iOS平台。

3

我正在使用Mapbox iOS SDK并尝试绘制一条没有GeoJSON的折线。我尝试使用以下方法获取路线:

func calculateRoute() {

    ...

    let options = NavigationRouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic)
    Directions.shared.calculate(options) { (waypoints, routes, error) in 
        guard let route = routes?.first else { return }
        self.showPreview(route: route)
    }
}

然后我尝试绘制一条路线。
func showPreview(route: Route) {

    guard let steps = route.legs.first?.steps else { return }
    var points = [CLLocationCoordinate2D]()
    for step in steps {
        points.append(step.maneuverLocation)
    }
    let line = MGLPolyline(coordinates: &points, count: UInt(points.count))
    mapView?.addAnnotation(line)
}

它在地图视图上绘制折线。我可以通过两个委托方法(MGLMapViewDelegate)改变折线的颜色和宽度。
func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat {
    return 10
}

func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
    return .blue
}

但是我找不到一种方法来设置折线周围的边框宽度和边框颜色。有什么办法可以做到这一点吗?

1个回答

6

看起来我有一个与您类似的用例(即不使用geojson),最终得到了类似于这样的东西。通过将您的路线与MGLLineStyleLayer相关联,您可以控制线条的视觉参数。

func showPreview(route: Route) {
    guard route.coordinateCount > 0 else { return }
    // Convert the route’s coordinates into a polyline
    var routeCoordinates = route.coordinates!
    let polyline = MGLPolylineFeature(coordinates: &routeCoordinates, count: route.coordinateCount)

    // If there's already a route line on the map, reset its shape to the new route
    if let source = mapView.style?.source(withIdentifier: "route-source") as? MGLShapeSource {
        source.shape = polyline
    } else {
        let source = MGLShapeSource(identifier: "route-source", features: [polyline], options: nil)

        // Customize the route line color and width
        let lineStyle = MGLLineStyleLayer(identifier: "route-style", source: source)
        lineStyle.lineColor = NSExpression(forConstantValue: UIColor.blue)
        lineStyle.lineWidth = NSExpression(forConstantValue: 3)

        // Add the source and style layer of the route line to the map
        mapView.style?.addSource(source)
        mapView.style?.addLayer(lineStyle)
    }
}

你想添加边框并控制其外观。如果你查看Mapbox网站上的这个示例:线条样式示例,他们通过创建第二个 MGLLineStyleLayer 并将其插入到第一个下面来实现你想要的效果。他们称第二层为 casingLayer。以下是他们的代码,可以看出它的形式与第一层相同。
let casingLayer = MGLLineStyleLayer(identifier: "polyline-case", source: source)
    // Add your formatting attributes here. See example on website.

然后他们将其插入到第一行下方,由于它的宽度更宽,因此显示为边框。
style.insertLayer(casingLayer, below: lineStyle)

希望这能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接