DEV Community

Cover image for Mapbox Demo: Bike route visualization color gradient and data scrubbing UX
Chris Whong for Mapbox

Posted on

Mapbox Demo: Bike route visualization color gradient and data scrubbing UX

A developer on Reddit recently asked for help building a ride playback feature with speed visualization on a Mapbox GL JS map. They had detailed GPS and speed data from a bike ride and wanted to show speed variations along the route.

The Challenge

The original question centered on two main requirements:

  1. Visualize speed variations along the route with color-coded gradients (slow = green, medium = yellow, fast = red)
  2. Interactive scrubbing that shows detailed speed and time data when the user hovers over any point on the route

The Solution

Here's the working implementation on codepen. The line visualizes the variations in speed along the bike trip. Move your mouse over the line to "scrub" and see data for a specific spot on the line.

Key Implementation Details

Speed Gradient
Instead of creating separate line segments for each speed zone, we use a single GeoJSON LineString with lineMetrics: true and build a dynamic gradient using the line-gradient paint property:

'line-gradient': [
  'interpolate',
  ['linear'],
  ['line-progress'],
  ...gradientStops  // Dynamically generated from speed data
]
Enter fullscreen mode Exit fullscreen mode

Each speed data point gets mapped to a position along the line (0 to 1) and assigned a color based on its speed value. Check out the official line-gradient example for more details on this technique.

A Note on Accuracy
This demo simplifies the gradient calculation by evenly distributing speed data points along the line based on timestamps. In a production app, you'd want to map each speed measurement to its actual GPS coordinate along the route for precise gradient placement. This ensures the gradient accurately reflects where speed changes occurred geographically, not just temporally.

Interactive Scrubbing
The scrubber uses geometry calculations to find the nearest point on the route as you move your mouse, then interpolates between speed data points to show accurate values at that location. A pink circle marker follows your cursor along the route, displaying the time and speed in a floating tooltip.

Performance Benefits

This approach renders a single line layer with a gradient instead of dozens of individual geometries, resulting in:

  • Faster initial render
  • Smooth interactions
  • Lower memory usage
  • Simpler state management

Cross-Platform Compatibility

While this example uses Mapbox GL JS for the web, the same line-gradient technique works on iOS and Android using the native Maps SDKs. The gradient expression syntax is consistent across all platforms.

Check out the full code in the CodePen above to see how the speed interpolation and distance calculations work. Happy mapping!

Top comments (0)