AJAX and JSONP in Leaflet
Allows you to call JSON via an Ajax call with a jsonp fallback.
var geojsonLayer = AJAX"geojson.json";
for jsonp add the option "dataType" and set it to "jsonp"
var geojsonLayer = LgeoJsonajax"http:webhost.fake/geojson.jsonp"dataType:"jsonp";
Note that data starts to download when the layer is created NOT when it’s added to the map in order to get a head start.
You may pass either a url string or an array of url strings if you want to download multiple things (handy if your downloading data from an ESRI based thing which will have separate line, point, and poly features).
As you see you can also use lower case methods without creating new objects
For weirder jsonp you can set "callbackParam" for if you need to change the name of the callback parameter to something besides "callback", e.g. Mapquest Nominative Open uses "json_callback" instead of "callback".
If you want to use
eval to parse JSON in older browsers you need to pass an option
evil set to something truthy.
If you want to be able to load stuff from the file system (with appropriate custom flags set) set local to true.
Gives off three events
data:loadingfires before we start downloading things, note if the constructor is given a url it won't wait to be added to the map to start downloading the data, but it does do an async wait so you have time to add a listener to it (and so leaflet.spin will work with it).
data:progressis called each time a file is downloaded and passes the downloaded geojson as event data.
data:loadedis called when all files have downloaded, this is mainly different from
data:progresswhen you are downloading multiple things.
You can also add a middleware function which is called after you download the data but before you add it to leaflet:
var geojsonLayer = LgeoJsonajax"route/to/esri.json"return esri2geoOrSomethingjson;;
addUrl does not clear the current layers but adds to the current one, e.g.:
var geojsonLayer = LgeoJsonajax"data.json";geojsonLayeraddUrl"data2.json";//we now have 2 layersgeojsonLayerrefresh;//redownload the most recent layergeojsonLayerrefresh"new1.json";//add a new layer replacing whatever is there
last but now least we can refilter layers without re adding them
var geojsonLayer = LgeoJsonajax"data.json";geojsonLayerrefilterreturn featurepropertieskey === values;;
Behind the scenes are two new classes L.Util.ajax = function (url) for same origin requests and L.Util.jsonp = function (url,options) cross origin ones. Both return promises, which have an additional abort method that will abort the ajax request.
In related news
L.Util.Promise is now a constructor for a promise, it takes one argument, a resolver function.
Some of the jsonp code inspired by/taken from this interesting looking plugin that I have failed to make heads nor tails of (the plugin, not the jsonp code)