Can’t Get Leaflet.js to Properly Render Amtrak Route Lines from GeoJSON (Zoom Breaks It)

Hey folks,

I’m working on a mapping project to show Amtrak train routes across the U.S. using Leaflet.js and custom-built GeoJSON files for each route (e.g., Empire Builder, Silver Star, etc.).

So far, I’m using L.geoJSON() to load each route onto the map, and it works at a basic level. But I’m running into three major issues:

  1. Zooming in/out distorts the lines or causes render issues
  2. Switching between routes doesn’t always clear the previous one
  3. Mobile performance is really laggy

Here’s a simplified version of my core code:

<div id="map" style="height: 600px;"></div>
<script>
  var map = L.map('map').setView([39.8283, -98.5795], 4); // Center of US

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors',
  }).addTo(map);

  var currentLayer;

  function loadRoute(routeName) {
    if (currentLayer) {
      map.removeLayer(currentLayer);
    }

    fetch(`/geojson/${routeName}.json`)
      .then(response => response.json())
      .then(data => {
        currentLayer = L.geoJSON(data, {
          style: { color: '#FF0000', weight: 3 },
        }).addTo(map);
        map.fitBounds(currentLayer.getBounds());
      })
      .catch(error => console.error('GeoJSON load error:', error));
  }

  // Example default route
  loadRoute('empire_builder');
</script>

What I’m trying to improve:

  • How can I make the zoom/pan experience smoother without redrawing every time?
  • Is there a better way to preload the route layers for quicker switches?
  • Are there known issues with Leaflet + GeoJSON that I’m missing?

This site seems to have figured it out perfectly:
Amtrak Routes Map
It loads instantly and handles zoom/pan without breaking the route lines.

Any insights would be hugely appreciated. I’ve been stuck tweaking styles and layer logic but not getting anywhere near that performance.

Hello, this could be a lot of things other then JS, do you have the viewport code in the head of the HTML and with CSS there’s a lot to do there if you still have issues. You could try the mobile first approach i.e. build a mobile website and slowly adding in the code for desktop.

Responsive Design