5

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?

  • 1
    The answer to «Is there any way to...?» is: yes. Maybe you should rephrase. – IvanSanchez May 11 '16 at 13:38
  • 3
    So I understand the logic behind your comment, but don't understand the why... Cheers for the reply though, very helpful! – cmca May 11 '16 at 14:08
4

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.

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.