Choropleth - Multiple Layers

Choropleth with multiple layers.

by Alex Azuero

HTML

<link rel="stylesheet" href="https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.css">
<script src="https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.js"></script>
<div id='map'></div>

<style>
.map-legend .swatch {
  width:20px;
  height:20px;
  float:left;
  margin-right:10px;
  }
.leaflet-popup-close-button {
  display: none;
  }
.leaflet-popup-content-wrapper {
  pointer-events: none;
  }
</style>
<script src='https://www.mapbox.com/mapbox.js/assets/data/us-states.js'></script>

CSS

body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }

JavaScript

L.mapbox.accessToken = 'pk.eyJ1IjoiY3lyaWwtbW9ib21vIiwiYSI6ImViMTcyOGZlZjZjZWI3ZTAyM2M2MDYzNmEwZTFiYmJhIn0.0pZ6ogddcufaUut-9sHozA';
  var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([37.8, -96], 4);

  var popup = new L.Popup({ autoPan: false });

  // statesData comes from the 'us-states.js' script included above
  var statesLayer = L.geoJson(statesData,  {
      style: getStyle,
      onEachFeature: onEachFeature
  }).addTo(map);
  
    var statesLayer1 = L.geoJson(statesData,  {
      style: getStyle,
      onEachFeature: onEachFeature
  }).addTo(map);
  

  var overlayMaps = {
    "s1": statesLayer,
    "s2": statesLayer1
};
L.control.layers('', overlayMaps).addTo(map);

  function getStyle(feature) {
      return {
          weight: 2,
          opacity: 0.1,
          color: 'black',
          fillOpacity: 0.7,
          fillColor: getColor(feature.properties.density)
      };
  }

  // get color depending on population density value
  function getColor(d) {
      return d > 1000 ? '#8c2d04' :
          d > 500  ? '#cc4c02' :
          d > 200  ? '#ec7014' :
          d > 100  ? '#fe9929' :
          d > 50   ? '#fec44f' :
          d > 20   ? '#fee391' :
          d > 10   ? '#fff7bc' :
          '#ffffe5';
  }

  function onEachFeature(feature, layer) {
      layer.on({
          mousemove: mousemove,
          mouseout: mouseout,
          click: zoomToFeature
      });
  }

  var closeTooltip;

  function mousemove(e) {
      var layer = e.target;

      popup.setLatLng(e.latlng);
      popup.setContent('<div class="marker-title">' + layer.feature.properties.name + '</div>' +
          layer.feature.properties.density + ' people per square mile');

      if (!popup._map) popup.openOn(map);
      window.clearTimeout(closeTooltip);

      // highlight feature
      layer.setStyle({
          weight: 3,
          opacity: 0.3,
          fillOpacity: 0.9
      });

      if (!L.Browser.ie && !L.Browser.opera) {
          layer.bringToFront();
 ...