我正在尝试将
line-gradient
应用到我的FeatureCollection,如下所示:
const progress = 0.5 // for simplification
map.setPaintProperty(
'track',
"line-gradient",
[
"step",
["line-progress"],
"rgba(255, 255, 255, 1)",
progress,
"rgba(0, 0, 0, 0)"
]
)
我的要素集合由多个要素组成,这些要素在地图上显示为一条长轨迹。我的目标是以编程方式显示/隐藏整个轨道的一部分。 相反,Mapbox GL 将
progress
应用于所有要素,而不是整个赛道(见图)。
我错过了什么?
感谢您的帮助
这可能对你有用;要以编程方式实现显示/隐藏整个轨道的一部分的相同效果,您需要结合使用 Mapbox GL JavaScript API 和数据操作来动态处理样式。
例如(假设您有一个名为
trackCollection
的 FeatureCollection)
// Merge all features into one MultiLineString feature
const turf = require('@turf/turf');
const mergedTrack = turf.combine(trackCollection);
// Calculate the cut-off point distance
const totalDistance = turf.length(mergedTrack);
const cutOffDistance = totalDistance * progress;
// Style the layer with data-driven properties
map.addLayer({
id: 'track-layer',
type: 'line',
source: {
type: 'geojson',
data: mergedTrack,
},
paint: {
'line-width': 2,
'line-gradient': [
'interpolate',
['linear'],
['line-progress'],
0, 'rgba(255, 255, 255, 1)', // Start of the track, full color
cutOffDistance, 'rgba(255, 255, 255, 1)', // Up to the cut-off point, full color
cutOffDistance + 0.1, 'rgba(0, 0, 0, 0)', // A bit after the cut-off point, transparent
1, 'rgba(0, 0, 0, 0)', // Rest of the track, transparent
],
},
});
它只是根据
cutOffDistance
值计算 progress
,然后对 "line-gradient"
使用数据驱动的属性,在其中创建从轨道起点到截止点的渐变,然后使轨道的其余部分透明。