Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <header>
  <nav class="navbar navbar-default navbar-fixed-top">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle glyphicon glyphicon-menu-hamburger" data-toggle="collapse" data-target="#navbar"></button>
      <a class="navbar-brand" href="#">Add GeoJSON to Leaflet Map</a>
    </div>
    <div class="collapse navbar-collapse" id="navbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a id="addJQ" href="#">jQuery getJSON</a></li>
        <li><a id="addVanillaJS" href="#">Vanilla JS (Fetch)</a></li>
        <li><a id="removeLayer" href="#">Remove Layer</a></li>
      </ul>
    </div>
  </nav>
</header>
<!-- container for map -->
<section id="map">
  <!-- display error message -->
  <span id="errorMsg"></span>
</section>
              
            
!

CSS

              
                /*** General ***/

html,
body,
#map {
  width: 100%;
  height: 100%;
}

body {
  padding-top: 50px;
}


/*** Navigation ***/

.navbar {
  margin-bottom: 0;
  padding: 0 15px;
  background: #4EB086;
}

.navbar-default .navbar-brand,
.navbar-default .navbar-brand:hover {
  color: #fff;
}

.navbar-default .navbar-brand {
  padding-left: 5px;
}

.navbar-default .navbar-brand:hover {
  cursor: default;
}

.navbar-toggle {
  background-color: #fff;
}

ul.nav.navbar-nav.navbar-right a {
  color: #fff;
  font-weight: bold;
  transition: color 0.4s;
}

ul.nav.navbar-nav.navbar-right li a:hover {
  color: #000;
}


/*** Error message at lower left of map ***/

#errorMsg {
  display: none;
  position: absolute;
  left: 15px;
  bottom: 10px;
  padding: 15px;
  background: #fff;
  color: #ff0000;
  font-weight: bold;
  z-index: 500;
}


/*** Map popup ***/

.map-popup {
  font-size: 1.25em;
  font-weight: bold;
}


/*** Control font size of title on small screens ***/

@media screen and (max-width: 400px) {
  .navbar-default .navbar-brand {
    font-size: 1em;
  }
}
              
            
!

JS

              
                "use strict";

/*** General Leaflet Code ***/
// Create map and center around Pittsburgh, PA
const map = L.map("map", {
  center: [40.44250530554684, -79.969482421875],
  zoom: 10
});

// Add Open Street Map as base map
const osm = L.tileLayer("//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>'
}).addTo(map);

/*** Code for adding GeoJSON ***/
// Allegheny County School Districts GeoJSON file
// Alleghency County, PA, Open GIS Data Site: https://openac-alcogis.opendata.arcgis.com/
const geoJsonUrl =
  "https://opendata.arcgis.com/datasets/f5ac385118344bbf8f707cd88ba31a45_0.geojson";

// Change to this url to test error function
// const geoJsonUrl = 'https://opendata.arcgis.com/datasets/f5ac385118344bbf8f707cd88ba31a45_0zzb3451.geojson';

// Placeholder for layer. Required to test if layer is added to map or not.
let schoolDistricts;

// HTML element to display error message
const errMsgSpan = $("#errorMsg");

/*** Add layer using Vanilla JS (Fetch API) ***/
const addDataFetch = () => {
  fetch(geoJsonUrl)
  .then((response) => {
    console.log(response);
    return response.json() })
  .then(function(data) {
     if (!mapHasLayer()) {
      // create a GeoJSON layer
      createSchoolDistrictsLayer(data);
    }
  })
  .catch(error => {
    errMsgSpan.text(`Request Failed: ${error.message}`);
    errMsgSpan.show();
  })
}

/*** Add layer using jQuery $.getJSON() method
See https://api.jquery.com/jquery.getjson/
1. Check to make sure layer is not already added to map.
2. Call $.getJSON method, passing in url for geoJSON data
3. Call function that creates Leaflet geoJSON layer and adds it to map
4. A function for the fail event is created to handle errors with the request
*******************************************************************************/

const addDataJQuery = () => {
  if (!mapHasLayer()) {
    const getLayerJQuery = $.getJSON(geoJsonUrl, function (data) {
      // create a GeoJSON layer
      createSchoolDistrictsLayer(data);
    }); // end getLayerJQuery()

    // If there is an error making the request, write the error out in the <span id="#errorMsg"> element
    getLayerJQuery.fail(function (jqxhr, textStatus, error) {
      const err = `${textStatus}, ${error} (${jqxhr.status})`;
      errMsgSpan.text(`Request Failed: ${err}`);
      errMsgSpan.show();
    }); // end getLayerJQuery().fail()
  } // end if (!mapHasLayer())
} // end addDataJQuery()

/*** Helper Functions ***/
// create GeoJSON layer, style, add popup, and add to map
const createSchoolDistrictsLayer = (data) => {
  // see http://leafletjs.com/reference.html#geojson
  schoolDistricts = L.geoJson(data, {
    // symbolize features
    style: function (feature) {
      return {
        color: "#000",
        weight: 3,
        opacity: 1,
        fillColor: "#EBE34D",
        fillOpacity: 0.5
      };
    },
    onEachFeature: function (feature, layer) {
      var name = feature.properties.NAME;
      var popupContent = L.Util.template(
        '<h2 class="map-popup">{SCHOOLD}</h2>',
        feature.properties
      );
      // add a popup to each feature
      layer.bindPopup(popupContent, {
        closeOnClick: true
      });
    }
  }).addTo(map); // add layer to map
}

// Test if map has layer
const mapHasLayer = () => {
  if (map.hasLayer(schoolDistricts)) {
    return true;
  } else {
    return false;
  }
}

// Remove layer from map
const removeLayerFromMap = () => {
  // if layer is on map, remove the layer
  if (mapHasLayer()) {
    map.removeLayer(schoolDistricts);
  }
}

/*** Event Handlers ***/
// Add layer with $.getJSON()
// tied to <a id="addJQ">
$("#addJQ").click(function () {
  addDataJQuery();
});

// Add layer with XMLHttpRequest()
// tied to <a id="addVanillaJS">
var addVanillaJS = document.getElementById("addVanillaJS");
addVanillaJS.addEventListener("click", addDataFetch);

// Remove layer from map
// tied to <a id="removeLayer">
$("#removeLayer").click(function () {
  removeLayerFromMap();
  errMsgSpan.hide();
});
              
            
!
999px

Console