Search code examples
javascriptjqueryleafletmapsmarkers

Use OpenWeather Icons as Markers on Leaflet Map


I'm trying to add the weather icons returned from an openweather API call to my leaflet map as markers but not getting any luck.

They will display in a pop up on the marker in an tag and when I console.log the iconUrl the link appears to the correct icon but they will only display as the default blue marker on the map - any ideas?

Relevant parts of my script:

var weatherMarker = L.markerClusterGroup();

(Inside Ajax Call success function):

if (result.status.name == "ok") {
                                        
    var temperature = Math.round(result.data[1].temp);
                                            
    var weatherIcon = L.icon({
     iconUrl: "http://openweathermap.org/img/w/" + result.data[1].icon + ".png",
     iconSize: [25, 30],
     iconAnchor: [22, 94],
     popupAnchor: [-3, -76],
                                });
                                            
weatherMarker.addLayer(new L.marker([lat, lng], {iconUrl: weatherIcon, crossOrigin: true})).bindPopup(temperature + " °C " + result.data[1].weather).addTo(mymap);
                                        
                                        
        ```

[![Appearance of Marker on the map][1]][1]


  [1]: https://i.sstatic.net/K1xgA.png


Solution

  • You need to add the option icon instead iconUrl:

    weatherMarker.addLayer(new L.marker([lat, lng], {icon: weatherIcon, crossOrigin: true})).bindPopup(temperature + " °C " + result.data[1].weather).addTo(mymap);