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:
- Zooming in/out distorts the lines or causes render issues
- Switching between routes doesn’t always clear the previous one
- 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.