I'm working on a route visualization tool using Leaflet.js to map Amtrak train routes. I'm loading station coordinates from a JSON array and creating markers with custom tooltips showing station names, cities, and codes.
Here's the core of my Javascript code:
var stationData = [
{ name: 'Chicago Union Station', code: 'CHI', lat: 41.8789, lng: -87.6400 },
{ name: 'Denver Union Station', code: 'DEN', lat: 39.7527, lng: -104.9994 },
{ name: 'Salt Lake City', code: 'SLC', lat: 40.7608, lng: -111.8910 }
// ... more
];
stationData.forEach(function(station) {
var marker = L.marker([station.lat, station.lng]).addTo(map);
var popupContent = `<strong>${station.name}</strong><br>Code: ${station.code}`;
marker.bindTooltip(popupContent, {
permanent: false,
direction: 'top',
offset: [0, -10],
className: 'station-tooltip'
});
});
The tooltips sometimes:
- Fail to render on specific zoom levels (especially when clustered)
- Don’t reappear after being closed
- Cause
undefinedvalues inpopupContenteven though the JSON data looks fine
Things I’ve tried:
- Wrapping the content generation in
setTimeout(no improvement) - Manually calling
marker.openTooltip()afterbindTooltip()(breaks hover logic) - Debugging
station.codevalues — confirmed they are not undefined
Here's a working map where I’m trying to replicate this behavior:
Amtrak Routes Map
My question:
Is there a common reason Leaflet tooltips silently fail when used in a data loop?
- Could DOM rendering timing affect dynamic tooltips?
- Should I be pre-processing the content strings before binding to avoid hidden async issues?
If it helps, I’m also using:
- Leaflet 1.9.4
- jQuery 3.6 (for other DOM tasks, not here)
- Vanilla JS (no React/Vue)