Change icon on leaflet

11,991

Solution 1

You should create instance (add new before myIconReplc), example, like this

var myIconReplc = L.Icon.extend({
    options: {
        iconUrl: "../resources/img/map/icons/orange/ambulance.png",
        iconSize: [30,35],
        shadowUrl: "../resources/img/map/icons/shadow.png",
        shadowAnchor: [8, 20],
        shadowSize: [25, 18],
        iconSize: [20, 25],
        iconAnchor: [8, 30] // horizontal puis vertical
    }
});

layer.on('click', function (e) {
   e.target.setIcon(new myIconReplc);
});

Solution 2

You've forgot the declare a new instance of your myIconReplc.

Change:

e.target.setIcon(myIconReplc);

To:

e.target.setIcon(new myIconReplc);

If you want to be able to declare an icon without the new like most of the classes in Leaflet you can do this:

// Normal extending
var MyIconReplc = L.Icon.extend({
    options: {
        iconUrl: "../resources/img/map/icons/orange/ambulance.png",
        iconSize: [30,35],
        shadowUrl: "../resources/img/map/icons/shadow.png",
        shadowAnchor: [8, 20],
        shadowSize: [25, 18],
        iconSize: [20, 25],
        iconAnchor: [8, 30] // horizontal puis vertical
    }
});

// Shorthand
var myIconReplc = function (options) {
    return new MyIconRepl(options);
}

Now you can do:

var icon = new MyIconReplc();

and:

var icon = myIconReplc();

You may have noticed that Leaflet objects are created without using the new keyword. This is achieved by complementing each class with a lowercase factory method

See: http://leafletjs.com/reference.html#class (under Class factories)

Share:
11,991

Related videos on Youtube

zelocalhost
Author by

zelocalhost

Updated on June 04, 2022

Comments

  • zelocalhost
    zelocalhost almost 2 years

    based on this question : https://gis.stackexchange.com/questions/54651/change-marker-icon-on-click-using-leaflet, i made this :

    // onEachFeature
    function onEachFeature(feature, layer) {
        layer.on('click', function (e) {
    
            // change icon
            console.log(layer.options.icon);
            e.target.setIcon(myIconReplc);
    
        });
    }
    
    var myIconReplc = L.Icon.extend({
        options: {
            iconUrl: "../resources/img/map/icons/orange/ambulance.png",
            iconSize: [30,35],
            shadowUrl: "../resources/img/map/icons/shadow.png",
            shadowAnchor: [8, 20],
            shadowSize: [25, 18],
            iconSize: [20, 25],
            iconAnchor: [8, 30] // horizontal puis vertical
        }
    });
    

    And i have this error : Uncaught TypeError: undefined is not a function

    What's wrong ?

    --- live : http://www.monde-du-rat.fr/pmr/new.php#/carte

  • zelocalhost
    zelocalhost about 9 years
    thks for your help :)
  • zelocalhost
    zelocalhost about 9 years
    thks for your help and additionnals explanations