Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import or require. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Behavior

Save Automatically?

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.

Editor Settings

Code Indentation

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

Visit your global Editor Settings.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <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 AJAX</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>
            
          
!
            
              /*** 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;
  }
}
            
          
!
            
              'use strict';

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

// Add Open Street Map as base map
var 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 ***/
// Pittsburgh Historic Districts GeoJSON file
// Pittsburgh Open GIS Data Site: https://pghgis.pittsburghpa.opendata.arcgis.com/
var geoJsonUrl = '//pghgis-pittsburghpa.opendata.arcgis.com/datasets/71df883dcf184292b69d5721df39b5dd_0.geojson'
// this is an alternate URL for the GeoJSON file
//var geoJsonUrl = '//pghgis-pittsburghpa.opendata.arcgis.com/datasets/71df883dcf184292b69d5721df39b5dd_0.geojson?where=&geometry={"xmin":-8926957.476723036,"ymin":4925457.3678345485,"xmax":-8878687.493361013,"ymax":4936922.92207731,"spatialReference":{"wkid":102100}}';

// Change to this url to test error function
//var geoJsonUrl = '//pghgis-pittsburghpa.opendata.arcgis.com/datasets/71df883dcf184292b69d5721df39b5zz_0.geojson';

// Placeholder for layer. Required to test if layer is added to map or not.
var pittHistDist;

// HTML element to display error message
var errMsgSpan = $('#errorMsg');

/*** 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
*******************************************************************************/

function addDataJQuery() {
  if (!mapHasLayer()) {
    var getLayerJQuery = $.getJSON(geoJsonUrl, function(data) {
      // create a GeoJSON layer
      createPittHistDistGeoJson(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) {
      var err = textStatus + ', ' + error + ' (' + jqxhr.status + ')';
      errMsgSpan.text('Request Failed: ' + err);
      errMsgSpan.show();
    }); // end getLayerJQuery().fail()
  } // end if (!mapHasLayer())
} // end addDataJQuery()

/*** Add layer using Vanilla JS to make an XML HTTP Request
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
1. Check to make sure layer is not already added to map.
2. Create a XMLHttpRequest
3. Open the request using GET method
4. Send the request
5. Request will cycle through states. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
6. Once the request is complete (4), if the request was successful (200), parse the request from string to JSON
See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
7. Call function that creates Leaflet geoJSON layer and adds it to map
8. If the response status is not 200, then an error message is generated
***********************************************************************************************************************/
// Add layer using vanilla AJAX request
function addDataVanillaJS() {
  if (!mapHasLayer()) {
    var getLayerVanillaJS = new XMLHttpRequest();
    getLayerVanillaJS.open('GET', geoJsonUrl);
    getLayerVanillaJS.send();

    getLayerVanillaJS.onreadystatechange = function(data) {
        if (getLayerVanillaJS.readyState === 4 && getLayerVanillaJS.status === 200) {          
            var geoJsonData = JSON.parse(getLayerVanillaJS.responseText);
            // create a GeoJSON layer
            createPittHistDistGeoJson(geoJsonData);
          } else if (getLayerVanillaJS.readyState === 4 && getLayerVanillaJS.status !== 200) {
            // add error message to span         
            var err = getLayerVanillaJS.statusText + ' (' + getLayerVanillaJS.status + ')';
            errMsgSpan.text('Request Failed: ' + err);
            errMsgSpan.show();          
        } // end if (getLayerVanillaJS.readyState === 4)
      } // end getLayerVanillaJS.onreadystatechange()
  } // if (!mapHasLayer())  
} // end addDataVanillaJS()

/*** Helper Functions ***/
// create GeoJSON layer, style, add popup, and add to map
function createPittHistDistGeoJson(data) {
  // see http://leafletjs.com/reference.html#geojson
  pittHistDist = 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">{NAME}</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
function mapHasLayer() {
  if (map.hasLayer(pittHistDist)) {
    return true;
  } else {
    return false;
  }
}

// Remove layer from map
function removeLayerFromMap() {
  // if layer is on map, remove the layer
  if (mapHasLayer()) {
    map.removeLayer(pittHistDist);
  }
}

/*** 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', addDataVanillaJS);

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

Console