DEV Community

Muhammad Tahir Farooq
Muhammad Tahir Farooq

Posted on

Optimizing GeoJSON Rendering Performance in Leaflet.js for High-Density Map Layers

When working on a recent data visualization project for mapping long-distance train routes, I ran into a performance bottleneck while trying to render high-density GeoJSON line data using Leaflet.js.

The issue wasn’t in basic rendering — Leaflet handles most static maps well. The challenge was in maintaining performance across zoom levels and dynamically switching between multiple layers (routes) on user interaction, especially on mobile.

🔧 Context:
The project involved visualizing Amtrak’s entire national network — long-distance routes like the Empire Builder, California Zephyr, Crescent, and more — in a scrollable, interactive interface.
For reference, here’s a working version I built:
🔗 Amtrak Routes Map

Each route was stored in its own GeoJSON file, and loaded dynamically on selection. Everything worked, until it didn’t.

🚧 Problem:
Switching between routes caused visible lag

On mobile, lines wouldn’t always draw properly without zoom interaction

Occasionally triggered Uncaught RangeError in the DOM layer stack when toggling too fast

✅ What Worked:
Minified GeoJSON

Reduced file sizes by stripping metadata

Converted multi-polylines into single FeatureCollection objects

Debounced Event Listeners

let routeLoadTimer;
function loadRouteSafely(routeName) {
  clearTimeout(routeLoadTimer);
  routeLoadTimer = setTimeout(() => loadRoute(routeName), 250);
}
Enter fullscreen mode Exit fullscreen mode

Viewport-Based Conditional Rendering

if (map.getZoom() > 4) {
  map.addLayer(currentLayer);
}
Enter fullscreen mode Exit fullscreen mode

🧪 Still Exploring:
Vector tile conversion for faster redraw

Switching to MapLibre or GL-based engines

Pre-rendered canvas caching on scroll idle

If anyone else is dealing with performance challenges in dynamic GeoJSON-heavy UIs, especially for real-time route switching or timeline filtering — I’d love to trade notes.

💡 Link Reference:
This is the live visualization I’ve been testing against:
Amtrak Routes Map

🏁 Final Thought:
Sometimes, the hardest part of building a “simple map” isn’t drawing lines — it’s keeping them smooth, responsive, and scalable for end users with unpredictable behavior.

Top comments (0)