显示和删除基于多层的图例

时间:2018-08-14 20:32:29

标签: leaflet legend

我有5层(var lev_layerGroup1 = new L.layerGroup();)等,需要使用两个不同的图例。我已经在下面尝试过此代码,但是在添加“无法读取未定义的属性addTo”和删除图层“无法读取未定义的属性删除”时出现错误,似乎它无法获取图层数据,因为它获取了“未定义” 。当我激活5个层中的任何一个甚至没有连接到图例的层时,都会出现错误。显示所有图层,但地图上没有图例。此代码示例有什么问题?谢谢

        function getColor(d) {
    switch(d) {
            case 1: return '#ff0000';
            case 2: return '#595959';
            case 3: return '#e78ac3';
            case 4: return '#8da0cb';
            case 5: return '#66c2a5';
            case 6: return '#fc8d62';
            default: return '#ffffff';
}
};

    function getColor2(d) {
    switch(d) {
            case 1: return '#ffffff';
            case 2: return '#595959';
            case 3: return '#e78ac3';
            case 4: return '#8da0cb';
            case 5: return '#66c2a5';
            case 6: return '#fc8d62';
            default: return '#ffffff';
}
};

var legend_day = L.control({position: 'bottomright'});

legend_day.onAdd = function (map) {

var legdiv = L.DomUtil.create('div', 'info legend'),
    grades = [1, 2, 3, 4, 5, 6],
    labels = ['00:00', '01:00 - 02:00', '02:30 - 03:30', '04:00', '04:30 - 06:00', '06:00 +'],
    title = [];

// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
    legdiv.innerHTML +=
        '<i style="background:' + getColor(grades[i]) + '"></i> ' +
        (grades[i] ? labels[i] + '<br>' : '+');
}

return legdiv;
};

var legend_eve = L.control({position: 'bottomright'});

legend_eve.onAdd = function (map) {

var legdiv = L.DomUtil.create('div', 'info legend'),
    grades = [1, 2, 3, 4, 5, 6],
    labels = ['00:00', '01:00 - 02:00', '02:30 - 03:30', '04:00', '04:30 - 06:00', '06:00 +'],
    title = [];

// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
    legdiv.innerHTML +=
        '<i style="background:' + getColor2(grades[i]) + '"></i> ' +
        (grades[i] ? labels[i] + '<br>' : '+');
}

return legdiv;
};

var overlayMaps = {

"lev1": lev_layerGroup1,
"lev2": lev_layerGroup2,
"lev3": lev_layerGroup3,
"lev4": lev_layerGroup4,
"lev5": lev_layerGroup5
};


var layerToLegendMapping={
"lev1": legend_day,
"lev2": legend_day,
"lev3": legend_day,
"lev4": legend_eve,
"lev5": legend_eve
}
function legendAdd(event) {
var layername = event.name;
map.addControl(layerToLegendMapping[layername]);
}
function legendRemove(event) {
var layername = event.name;
map.removeControl(layerToLegendMapping[layername]);
}
map.on('overlayadd',legendAdd);
map.on('overlayremove',legendRemove);


    L.control.layers( {
        "OpenStreetMap": osm.addTo(map),
    }, 
    {
    'Day 1': lev_layerGroup1,
    'Day 2': lev_layerGroup2,
    'Day 3': lev_layerGroup3,
    'Evening Day 1': lev_layerGroup4,
    'Evening Day 2': lev_layerGroup5
    }, 
    { position: 'topright', collapsed: true }).addTo(map);

0 个答案:

没有答案