Simple GeoJSON filter example in Leaflet

by Nikolay Petrov

HTML

<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<div id="map"></div>

CSS

html, body, #map {
      height: 100%;
      width:100%;
      padding:0px;
      margin:0px;
   }

JavaScript

/////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
/////////////////////////////////////////////////////////////////////////////////////////////
var map = L.map('map').setView([34.05,-118.25], 11);
ATTR = '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a> | ' +
'&copy; <a href="http://cartodb.com/attributions">CartoDB</a>';
CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
L.tileLayer(CDB_URL, {attribution: ATTR}).addTo(map);

/////////////////////////////////////////////////////////////////////////////////////////////
//adding data//
/////////////////////////////////////////////////////////////////////////////////////////////
var myJson = getJson();
var polyLayer = L.geoJson(myJson, {filter: layerFilter}).addTo(map);

//polyLayer will only include features for which this function returns true
function layerFilter(feature) {
  if (feature.properties.show === "yes") return true
}

/////////////////////////////////////////////////////////////////////////////////////////////
//GeoJSON goes here//
/////////////////////////////////////////////////////////////////////////////////////////////
function getJson() {
  return {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {"show": "yes"},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -118.28417301177979,
              34.044943339775706
            ],
            [
              -118.27032208442688,
              34.066667470321896
            ],
            [
              -118.28438758850098,
              34.07278193318909
            ],
            [
              -118.28460216522215,
              34.095813853077765
            ],
            [
              -118.19259166717528,
              34.09577831481821
        ...