Skip to content

Instantly share code, notes, and snippets.

@gimoya
Created December 27, 2018 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gimoya/d6d425be75f2ea3354c56191b1e18b76 to your computer and use it in GitHub Desktop.
Save gimoya/d6d425be75f2ea3354c56191b1e18b76 to your computer and use it in GitHub Desktop.
Add GeoJSON to Leaflet Map

Add GeoJSON to Leaflet Map

A demonstration of how to add geoJSON data to a Leaflet map. The demo uses jQuery's getJSON method and a vanilla XMLHttpRequest.

This demo is for the 1.x release of Leaflet.js.

GeoJSON data is provided by the City of Pittsburgh, Pennsylvania.

A Pen by Captain Anonymous on CodePen.

License.

<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>
'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();
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
/*** 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;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment