TrackAsiaTrackAsia GL JS DocsExamplesCreate a gradient line using an expression

Create a gradient line using an expression

Use the line-gradient paint property and an expression to visualize distance from the starting point of a line.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Create a gradient line using an expression</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://unpkg.com/trackasia-gl@1.0.5/dist/trackasia-gl.js"></script>
<link href="https://unpkg.com/trackasia-gl@1.0.5/dist/trackasia-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = (window.map = new trackasiagl.Map({
container: 'map',
style: 'https://maps.track-asia.com/styles/v1/streets.json?key=public_key',
center: [106.720772,10.77423],
zoom: 14
}));
var geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {},
'geometry': {
'coordinates': [[106.716666,10.771724],[106.716387,10.773832],[106.717031,10.775835],[106.714176,10.777268],[106.715164,10.778638],[106.716087,10.777964],[106.717075,10.77887],[106.718341,10.777247],[106.722206,10.778491],[106.72255,10.776657],[106.722271,10.774528],[106.72255,10.773463],[106.732306,10.778378]],
'type': 'LineString'
}
}
]
};
map.on('load', function () {
// 'line-gradient' can only be used with GeoJSON sources
// and the source must have the 'lineMetrics' option set to true
map.addSource('line', {
type: 'geojson',
lineMetrics: true,
data: geojson
});
// the layer must be of type 'line'
map.addLayer({
type: 'line',
source: 'line',
id: 'line',
paint: {
'line-color': 'red',
'line-width': 14,
// 'line-gradient' must be specified using an expression
// with the special 'line-progress' property
'line-gradient': [
'interpolate',
['linear'],
['line-progress'],
0,
'blue',
0.1,
'royalblue',
0.3,
'cyan',
0.5,
'lime',
0.7,
'yellow',
1,
'red'
]
},
layout: {
'line-cap': 'round',
'line-join': 'round'
}
});
});
</script>
</body>
</html>