lundi 11 janvier 2016

Checkbox to show/hide a map overlay using mapbox?

I am new to Javascript, and I have a basic checkbox question to show/hide my geojson poverty data. I am trying to show this data as a choropleth map overlay on a mapbox baselayer upon checking the "Show Poverty Data" checkbox (here is the link). I am able to click on the checkbox to show/hide the overlay once, but after the first round of checking/unchecking, the overlay stops showing. Please help!!

L.mapbox.accessToken = 'pk.eyJ1IjoiemFrc2Nsb3NldCIsImEiOiJjaWY2dWxkc2gwcXBjczVtM3pnc3hydnI1In0.ABQHwIrVx95WhAVv_2JPeA';

var map = L.mapbox.map('map')
  .setView([40.71, -74.00], 11)
  .addLayer(L.mapbox.tileLayer('mapbox.dark'));


function getColor(d) {
  return d > 30 ? "#0868ac" :
    d > 20 ? "#43a2ca" :
    d > 10 ? "#7bccc4" :
    d > 0 ? "#a8ddb5" :
    "grey";
};

//load poverty data
var povertyData = "http://ift.tt/1K9f6YV";

$.getJSON(povertyData, function(povertyData) {

  //get unique poverty % values
  var povertyFeatures = povertyData.features;
  var uniquePoverty = [];

  povertyFeatures.forEach(function(x) {
    if (!povertyFeatures[x.properties.PopInPover]) {
      uniquePoverty.push(x.properties.PopInPover);
      povertyFeatures[x.properties.Poverty] = true;
    }
  });

  console.log(povertyData);
  console.log(uniquePoverty);

  //styling the choropleth
  function style(feature) {
    return {
      fillColor: getColor(feature.properties.PopInPover),
      weight: 1,
      opacity: 0.3,
      color: "#000",
      dashArray: "1",
      fillOpacity: 0.3
    };
  };

  //add poverty data
  var addPovertyData = L.geoJson(povertyData, {
    style: style
  });

  //checkbox event to overlay poverty data
  $(".checkbox-primary").click(function() {
    if (this.checked) {
      console.log("checked!");
      addPovertyData.addTo(map);
    } else {
      console.log("unchecked!");
      addPovertyData.clearLayers();
    };
  });
});



Aucun commentaire:

Enregistrer un commentaire