Skip to content

Instantly share code, notes, and snippets.

@blahah
Last active February 8, 2023 09:04
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

  • see which browsers support fetch: http://caniuse.com/#feat=fetch
  • you can 'polyfill' fetch for browsers that don't support it using https://github.com/github/fetch
    • polyfilling is where you add a feature to JS that isn't supported natively in the browser, by loading a library that adds the same functionality as if it were natively supported
  • or use a service that auto-polyfills the fetch function in any browser that's missing it: https://polyfill.io/v2/docs/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment