我正在将我的应用程序移至 Mapbox,而我坚持的一件事是创建一条多色折线,其中线段颜色由速度动态设置。我能做的最接近的事情是创建一组不同颜色的线,并将它们添加到地图中,就像许多单独的线一样,但是处理时间和帧速率下降太多了,更不用说你可以看到不同的部分了。这很容易通过 MapKit 或谷歌地图实现,但据我所知,折线在 Mapbox 中只能有一种颜色。
在这里提出了一个非常相似的问题,但那是 3 年前的事了,答案似乎与使用方向 API 有关。
基本功能如下所示,我创建了一个自定义 MGLMulticolorPolyline 类,以便我可以设置颜色
func locationPolyLine(locations : [Location], averageSpeed: Double, topSpeed: Double) -> [MGLMulticolorPolyline] {
var coordinates: [(CLLocation, CLLocation)] = []
var speeds: [Double] = []
let smallerLocationArray = locations.enumerated().filter({ index, _ in
index % 2 != 0
}).map { $0.1 }
for (first, second) in zip(smallerLocationArray, smallerLocationArray.dropFirst()) {
//create an array of coordinates
let start = CLLocation(latitude: first.locLatitude, longitude: first.locLongitude)
let end = CLLocation(latitude: second.locLatitude, longitude: second.locLongitude)
coordinates.append((start, end))
let distance = end.distance(from: start)
guard let firstTimestamp = first.locTimestamp,
let secondTimestamp = second.locTimestamp else {continue}
let time = secondTimestamp.timeIntervalSince(firstTimestamp as Date)
let speed = time > 0 ? distance / time : 0
speeds.append(speed)
}
var segments: [MGLMulticolorPolyline] = []
var index = 0
for ((start, end), speed) in zip(coordinates, speeds) {
let coords = [start.coordinate, end.coordinate]
let segment = MGLMulticolorPolyline(coordinates: coords, count: 2)
if smallerLocationArray[index].lift == true{
segment.color = UIColor.blue
} else{
segment.color = segmentColor(speed: speed,
midSpeed: averageSpeed,
slowestSpeed: 0.0,
fastestSpeed: topSpeed)
}
segments.append(segment)
index += 1
}
return segments
}
}
它像这样被添加到地图中
let multiColoredPolyline = MapboxHelper().locationPolyLine(locations: locationsArray, averageSpeed: avgSpeed, topSpeed: maxSpeed)
mapView.addAnnotations(multiColoredPolyline)