Search code examples
javascriptleafletleaflet.markercluster

Custom Leaflet icons not showing up when generated in a loop


I am using Leaflet to create a project that would display certain POIs on the map, based on user specified country information. I am having trouble displaying the icon and title attribute for these markers under certain circumstances.

When I use this code, everything works exactly as expected. The custom icon is showing correctly on the marker and when I hover on the marker I can see the text 'airport':

let airports = L.markerClusterGroup({
  showCoverageOnHover: false,
});

const airportMarker = L.icon({
  iconUrl: "media/plane-line.png",
  iconSize: [24, 24]
})

airports.addLayer(L.marker([52.5, -0.09], {
  icon: airportMarker,
  title: "airport"
})

map.addLayer(airports)

However, I am using tomtom API to get airport coordinates and names, then populate the markers on the map. For this I am using a for loop and here is where the issue occurs. This code does generate the correct coordinates for each airport but uses the default Leaflet marker icon and does not show the title attribute on hover:

//  the data object is passed after successful ajax call

let airports = L.markerClusterGroup({
  showCoverageOnHover: false,
});

const airportMarker = L.icon({
    iconUrl: "media/plane-line.png",
    iconSize: [24, 24]
})

for(let i = 0; i < Object.keys(data).length; i++) {
    const name = Object.keys(data)[i]
    const coordinates = Object.values(data)[i]

    airports.addLayer(L.marker(coordinates), {
        icon: airportMarker,
        title: name
    })
}

map.addLayer(airports)

Any help or tips would be appreciated!


Solution

  • The issue was that I was not creating a new L.marker() for each new marker. This code fixed the issue:

    //  the data object is passed after successful ajax call
    
    let markers = L.markerClusterGroup({
      showCoverageOnHover: false,
    });
    
    const airportMarker = L.icon({
        iconUrl: "media/plane-line.png",
        iconSize: [24, 24]
    })
    
    for(let i = 0; i < Object.keys(data).length; i++) {
        const name = Object.keys(data)[i]
        const coordinates = Object.values(data)[i]
        const airport = new L.marker(coordinates, { // here is where my mistake lies
            icon: icon,
            title: name
        }
        markers.addLayer(airport)
    
    }
    map.addLayer(markers)
    

    Thanks to this post for a hint as to what I was doing wrong.