6

I have a leaflet map that consists of various wms layers representing different years.

I am trying to add a legend to my leaflet map but with my own custom hex colours instead of trying to use a layer in the map (as my legend is more broad) This is the sample code from leaflets website.

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

legend.onAdd = function (map) {

    var div = L.DomUtil.create('div', 'info legend'),
    grades = [0, 10, 20, 50, 100, 200, 500, 1000],
    labels = [];

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

return div;
};

legend.addTo(map);

Is there anyway to adapt this to my own 5 class hex(colors) legend?

0
5

The legend does not depend on the existence of any particular layer. The part that you are missing here is a getColor function. Copying the one from the tutorial in question:

function getColor(d) {
    return d > 1000 ? '#800026' :
           d > 500  ? '#BD0026' :
           d > 200  ? '#E31A1C' :
           d > 100  ? '#FC4E2A' :
           d > 50   ? '#FD8D3C' :
           d > 20   ? '#FEB24C' :
           d > 10   ? '#FED976' :
                      '#FFEDA0';
}

You see that the breaks are the same as the grades specified in the legend control:

grades = [0, 10, 20, 50, 100, 200, 500, 1000]

If you adjust these breakpoints to your needs and set the colors accordingly, you will have the legend you want.

0
0
var legend = L.control({position: 'bottomleft'});
legend.onAdd = function (map) {

var div = L.DomUtil.create('div', 'info legend');
labels = ['<strong>Categories</strong>'],
categories = ['Road Surface','Signage','Line Markings','Roadside Hazards','Other'];

for (var i = 0; i < categories.length; i++) {

        div.innerHTML += 
        labels.push(
            '<i class="circle" style="background:' + getColor(categories[i]) + '"></i> ' +
        (categories[i] ? categories[i] : '+'));

    }
    div.innerHTML = labels.join('<br>');
return div;
};
legend.addTo(map);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.