Skip to content

Instantly share code, notes, and snippets.

@blahah
Last active February 8, 2023 09:04
Show Gist options
  • Save blahah/167a363844326c2192d7ab0ff32ad8d0 to your computer and use it in GitHub Desktop.
Save blahah/167a363844326c2192d7ab0ff32ad8d0 to your computer and use it in GitHub Desktop.
loading geoJSON examples
// we have a geoJSON file (in this case for Guinea) on the web:
var guinea = 'https://raw.githubusercontent.com/johan/world.geo.json/master/countries/GIN.geo.json'
// and we have a function that does something with the geoJSON file:
var handleGeoJSON = function (data) {
// data is the JSON parsed into a JS object
console.log(data)
}
// using jquery (you must have loaded jQuery first) - http://api.jquery.com/jquery.getjson
// this is the shortest amount of code for you to write but you have to include a huge library to be able to use it
$.getJSON(guinea, handleGeoJSON)
// using the native browser fetch API - https://developer.mozilla.org/en/docs/Web/API/Fetch_API
// this requires a tiny bit more code from you but no dependencies (only works in modern browsers)
fetch(guinea).then(function(response) { return response.json() }).then(handleGeoJSON)
// you can load a geoJSON file into a leaflet map super easily using
// the geoJSON method - see http://leafletjs.com/examples/geojson/
// in modern browsers you can use JS features from newer versions of the specification
// note that JS is called ECMAScript in the standards, see e.g. https://babeljs.io/learn-es2015/
// same geoJSON as before
var guinea = 'https://raw.githubusercontent.com/johan/world.geo.json/master/countries/GIN.geo.json'
// create a leaflet map (you must have loaded leaflet first)
var map = L.map('mapid')
fetch(
guinea
).then(
res => res.json()
).then(
data => L.geoJSON(data).addTo(map)
)

extra info if you want to dig deeper:

1. fetch() returns a promise

2. not all browsers have fetch yet - and those that do only support it in more recent versions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment