Has*_*esh 3 border polyline mapbox swift
我正在使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我试着画了一条路线。
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)
}
Run Code Online (Sandbox Code Playgroud)
它在地图视图上绘制一条折线。我可以使用两个委托方法 (MGLMapViewDelegate) 更改折线的颜色和宽度:
func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat {
return 10
}
func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
return .blue
}
Run Code Online (Sandbox Code Playgroud)
但我找不到在折线周围设置边框宽度和边框颜色的方法。有没有办法做到这一点?
看起来我有一个与您类似的用例(即不使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
您想添加边框并控制其外观。如果您在 Mapbox 网站上查看此示例:线条样式示例,他们会通过创建第二个MGLLineStyleLayer并将其插入第一个下方来执行您想要的操作。他们称之为第二层casingLayer。这是他们的代码,因此您可以看到它的形成方式与第一层相同。
let casingLayer = MGLLineStyleLayer(identifier: "polyline-case", source: source)
// Add your formatting attributes here. See example on website.
Run Code Online (Sandbox Code Playgroud)
然后他们将它插入到第一行下方,因为它的宽度更宽,所以显示为边框。
style.insertLayer(casingLayer, below: lineStyle)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。