How to change legends on multiple choropleth maps using Mapbox

I created a multiple choropleth map using the Mapbox Guide , and would like to disable legends based on what the current data layer is.

This is the function I'm trying to use to change the legend:

function changeLegend() {
    var previousLegend = $('.map-legends').html()
    map.legendControl.removeLegend(previousLegend)
    map.legendControl.addLegend(getLegendHTML());
}

But he does not delete legends properly, he simply adds them to each other. When I delete legends using jQuery instead map.legendControl.removeLegend, the previous legend is deleted, but when I call map.legendControl.addLegend, it adds two legends, even if the function that generates the html legends is hit only once.

Did someone help me remove and add legends?

+4
source share
1

, , L.mapbox.legendControl, , , ,

  • map.legendControl._legends - , , , map.legendControl.addLegend, map.legendControl.removeLegend ,

.

// at this point:
//   map.legendControl._legends = {}

map.legendControl.addLegend('<span>hello world</span>')
// at this point:
//   map.legendControl._legends = {
//     '<span>hello world</span>': 1
//   }

map.legendControl.addLegend('random string')
// at this point:
//   map.legendControl._legends = {
//     '<span>hello world</span>': 1,
//     'random string': 1
//   }

map.legendControl.addLegend('random string')
// at this point:
//   map.legendControl._legends = {
//     '<span>hello world</span>': 1,
//     'random string': 2
//   }

map.legendControl.removeLegend('random string')
// at this point:
//   map.legendControl._legends = {
//     '<span>hello world</span>': 1,
//     'random string': 1
//   }

, , , , ( , addLegend removeLegend _update

  • _legend, <div class="map-legend wax-legend"></div> ( _legend[some key] , ).

: html ,

<div class="map-legend wax-legend"><span>hello world</span></div>
<div class="map-legend wax-legend">random string</div>

.map-legends

<div class="map-legends wax-legends leaflet-control">
  <div class="map-legend wax-legend"><span>hello world</span></div>
  <div class="map-legend wax-legend">random string</div>
</div>

, var previousLegend = $('.map-legends').html(), , , , <div class="map-legend">,

, $('.map-legends').html(), html, ,

var previousLegend;
function changeLegend() {
  if (previousLegend) map.legendControl.removeLegend(previousLegend)
  var newLegend = getLegendHTML();
  map.legendControl.addLegend(newLegend);
  previousLegend = newLegend;
}
+1
source

All Articles