Skip to content

Instantly share code, notes, and snippets.

@tyrasd
Last active February 1, 2016 09:36
Show Gist options
  • Save tyrasd/7b88251726d3da9152ed to your computer and use it in GitHub Desktop.
Save tyrasd/7b88251726d3da9152ed to your computer and use it in GitHub Desktop.
Leaflet GeoJSON viewer

Opens the GeoJSON supplied via GET-data on a basic leaflet map. Supports some styling of features via simplestyle properties.

Parameters:

  • geojson - the data to display on the map
  • location - initial map center location: "lon,lat,zoom" or "auto" (default)

Examples:

<!DOCTYPE html>
<html>
<head>
<title>Leaflet GeoJSON viewer</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--leaflet-->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>
</head>
<body>
<div id="map" style="position:absolute; top:0; left:0; right:0; bottom:0;"></div>
<script>
var params = {};
location.search.slice(1).split('&').forEach(function(param) {
param = param.split('=');
params[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
});
var map = L.map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
var geojsonLayer = L.geoJson(JSON.parse(params.geojson), {
style: function(feature) {
var stl = {}
function addStyleDefinition(leafl, simplest) {
if (feature.properties[simplest] !== undefined)
stl[leafl] = feature.properties[simplest];
}
addStyleDefinition('color', 'stroke');
addStyleDefinition('weight', 'stroke-width');
addStyleDefinition('opacity', 'stroke-opacity');
addStyleDefinition('fillColor', 'fill');
addStyleDefinition('fillOpacity', 'fill-opacity');
return stl;
}
}).addTo(map);
if (params.location !== undefined && params.location !== 'auto') {
var loc = params.location.split(',');
map.setView(L.latLng(loc.slice(0,2).reverse()), loc[2]);
} else {
map.fitBounds(geojsonLayer.getBounds(), { padding: [10,10] });
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment