1

I'm trying to add custom labels in a leaflet map I built for my company. The legend code is based off of the tutorial for a choropleth map. So far it looks like this.

Legend without identifiers

The code I have for the legend is

legend.onAdd = function (map) {

    var div = L.DomUtil.create('div', 'info legend');
    var grades = [0,50,100,150, 200, 250, 300, 350, 400, 450, 500, 1000];
    var labels = [];
    var from, to;

    for (var i = 0; i < grades.length; i++) {
        from = grades[i];
        to = grades[i + 1];

        labels.push ( 
            'least expensive' + '<i style="background:' + getColor(from + 1) + '"></i> '  
            +);
    }

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

legend.addTo(map);`

My issue is, when I try to just add in text before the color box in labels.push, it ends up looping for each color enter image description here

I only want the top and bottom to be labeled, top being "least expensive" and bottom being "most expensive"

Any advice? I'm still fairly novice with HTML.

1
  • Thank you, just adjusted it! Sep 7, 2022 at 17:18

1 Answer 1

1

This is really basic HTML/JS question and should be asked on StackOverflow, but anyway ...

Instead of adding same text to every legend element you have to add appropriate text only to the first and the last element. Code could then look something like this:

legend.onAdd = function (map) {
  var div = L.DomUtil.create('div', 'info legend');
  var grades = [0,50,100,150, 200, 250, 300, 350, 400, 450, 500, 1000];
  var labels = [];
  var from, to;

  for (var i = 0; i < grades.length; i++) {
    from = grades[i];
    to = grades[i + 1];
    labels.push ( 
      '<i style="background:' + getColor(from + 1) + '"></i> '  
    );
  }
  labels[0] += 'least expensive';
  labels[grades.length - 1] += 'most expensive';
  div.innerHTML = labels.join('<br>');
  
  return div;
};
2
  • Thank you so much, I'm super new with HTML and found leaflet discussions here, I'll be sure to move over to SO from now on Sep 7, 2022 at 20:47
  • It depends on your question. If it's GIS related, you should place it here, otherwise on StackOverflow. If you are not sure about the nature of the question, you can also start here if it's at least remotely GIS related.
    – TomazicM
    Sep 7, 2022 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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