Search code examples
javascriptleafletlegendgeojson

Create legend with different circle sizes in Leaflet


Good afternoon,

I am fighting with the leaflet legend dependant on the circle radius. Because I am going to have the values with the same colour, but different size. I would like to create legend appropriate to them.

I tried this example:

http://jsfiddle.net/nathansnider/o563bg44/5/

to implement into my map.

For this purpose I used the following code:

   function getRadius(r) {
//r = Math.sqrt(y / Math.PI)
//return r;
return r > 100 ? 15 :
       r > 50 ? 10 :
       r > 20 ? 6 :
       r > 10 ? 3 :
       0;
 }


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

var div = L.DomUtil.create('div', 'info legend');
grades = [0, 10, 20, 50, 100],
labels = ['<strong>Amount of units</strong>'],
categories = ['> 100','50-100','1-50','N/A'];

for (var i = 0; i < grades.length; i++) {
    labels.push(
        '<i class="circlepadding" style="width: '+Math.max(0,(19-1.8*getRadius))+'px;"></i> <i 
 style="background: #8080A0; width: '+getRadius*2+'px; height: '+getRadius*2+'px; border-radius: 
 50%; margin-top: '+Math.max(0,(9-getRadius))+'px;"></i> ');
}
div.innerHTML = labels.join('<br>');
return div;
 };
  legend.addTo(map);

but finally I got a poor result as per in the picture below:

enter image description here

Could someone help me with this problem?


Solution

  • Change your for-loop to:

    for (var i = 0; i < grades.length; i++) {
                var grade = grades[i]*5;
          labels.push(
              '<i class="circlepadding" style="width: 5px;"></i> <i  style="background: #8080A0; width: '+getRadius(grade)*2+'px; height: '+getRadius(grade)*2+'px; border-radius:  50%; margin-top: '+Math.max(0,(9-getRadius(grade)))+'px;"></i> '+categories[i]);
      }
    

    And you have to add one more category:

    categories = ['> 100','50-100','1-50','N/A','XX'];