user21804835
user21804835

Reputation: 1

How to change only one property of leaflet layer icon?

I have Leaflet icons on the map, and I want to change these icons to other icons. But I want to change only their iconUrl, leaving the other parameters (iconSize, iconAnchor, popupAnchor) unchanged.

I have a code like this:

let icoFile = 'blue-circle.svg';
        
const CircleIcon = L.Icon.extend({
    options: {iconUrl: icoFile, popupAnchor: [0, 0]}
});

let ico_5 = new CircleIcon({iconSize: [5, 5], iconAnchor: [3,3]});
let ico_9 = new CircleIcon({iconSize: [9, 9], iconAnchor: [5,5]});
let ico_13 = new CircleIcon({iconSize: [13, 13], iconAnchor: [7,7]});
let ico_17 = new CircleIcon({iconSize: [17, 17], iconAnchor: [9,9]});

//...

const markers = L.layerGroup();
a_marker = L.marker([52, 17], {icon: ico_17}, {alt: 'a_alt'}).bindPopup("a_desc").addTo(markers);
//b_marker = ...
//a lot of markers added this way

// ...

const btn_apply = document.querySelector('#apply');
btn_apply.addEventListener('click', function(e)
{
    const checked_red_ico = document.querySelector('#checkbox_red_ico').checked;
    if(checked_red_ico)
        icoFile = 'red-circle.svg';
    else
        icoFile = 'blue-circle.svg';
    console.log(icoFile);
    markers.eachLayer(function (layer)
    {
        layer.setIcon(/* ??? */);
    });
});

If in place of /* ??? */ I type a specific icon, for example, ico_13, then all the icons on change to ico_13 (blue).

I have no idea what to type in this place to make the icons change to red. I tried writing something like (probably stupid) {options: {iconUrl: icoFile, popupAnchor: [0, 0], iconSize: layer.setIcon().iconSize, iconAnchor: layer.setIcon().iconAnchor}} but it didn't work.

How should I write it to make it work properly?

Upvotes: 0

Views: 183

Answers (1)

Svystun
Svystun

Reputation: 86

If you're using layers group you will need to write 2 getLayer functions like this

function changeIcon(){  
    markers.eachLayer(function (layer)
    {
        
        layer.eachLayer(function (lyr){
            
            const checked_red_ico = document.querySelector('#checkbox_red_ico').checked;
            if(checked_red_ico){
                icoFile = 'red-circle.svg';
            } else {
                icoFile = 'blue-circle.svg';
            }
            var newIcon =  L.icon({
                iconUrl: icoFile,
                iconSize: lyr.defaultOptions.icon.options.iconSize,
                iconAnchor: lyr.defaultOptions.icon.options.iconAnchor
            });         
            lyr.setIcon(newIcon);
        });
    });
}

Upvotes: 0

Related Questions