更改传单上的图标

Change icon on leaflet

基于这个问题:https://gis.stackexchange.com/questions/54651/change-marker-icon-on-click-using-leaflet,我做了这个:

// 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
    }
});

我有这个错误:Uncaught TypeError: undefined is not a function

怎么了?

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

您应该创建实例(在 myIconReplc 之前添加 new),example,像这样

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);
});

您忘记了声明 myIconReplcnew 实例。

变化:

e.target.setIcon(myIconReplc);

收件人:

e.target.setIcon(new myIconReplc);

如果你想像 Leaflet 中的大多数 类 一样声明一个没有 new 的图标,你可以这样做:

// 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);
}

现在你可以做:

var icon = new MyIconReplc();

和:

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

参见:http://leafletjs.com/reference.html#class(在 Class 工厂下)