如何在mapbox iOS中绘制路线上获取注释图像

时间:2018-04-09 17:26:19

标签: swift mapbox

Annotations show under the drawn route

我的计算路线的代码如下:

func calculateRoute(waypoints: [Waypoint],
                    completion: @escaping (Route?, Error?) -> ()) {

    // Coordinate accuracy is the maximum distance away from the waypoint that the route may still be considered viable, measured in meters. Negative values indicate that a indefinite number of meters away from the route and still be considered viable.
    let startPoint = Waypoint(coordinate: currentLocation, coordinateAccuracy: -1, name: "Origin")
    var waypointsWithCurrentLoc = waypoints
    waypointsWithCurrentLoc.insert(startPoint, at: 0)

    let options = NavigationRouteOptions(waypoints: waypointsWithCurrentLoc, profileIdentifier: .automobile)
    // Generate the route object and draw it on the map
    _ = Directions.shared.calculate(options) { [unowned self] (waypoints, routes, error) in
        if error != nil{
            print("Error occured:", error)
        }
        else{
            self.directionsRoute = routes?.first
            // Draw the route on the map after creating it
            self.drawRoute(route: self.directionsRoute!)
        }
    }
}

我绘制路线的代码如下:

func drawRoute(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 = map.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 = MGLStyleValue(rawValue: #colorLiteral(red: 0.2796384096, green: 0.4718205929, blue: 1, alpha: 1))
        lineStyle.lineWidth = MGLStyleValue(rawValue: 8)

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

我的代码出了什么问题?它返回一条较长的折线,因为我正在计算一个优化的路线,其中注释只是在路上停下来。

2 个答案:

答案 0 :(得分:3)

我发现无需添加层,而是可以将其插入最后一层。 因此,在您的drawRoute(route:Route)函数中,您必须将最后一行更改为:

if let style = mapView.style, let last = style.layers.last {
    mapView.style?.insertLayer(lineStyle, below: last)
}
else {
    mapView.style?.addLayer(lineStyle)
}

看起来有点像hack,因为我们不确定最后一层是带有注释的图层,但如果地图上只有一个溃败,则此代码可能会起作用。

此示例仅表示可以快速轻松地解决问题,但最终需要安全

答案 1 :(得分:0)

答案是无法将Z索引控件添加到地图样式中,您必须创建折线,然后在图层顶部添加注释作为单独的MapStyle元素。