Wednesday, September 26, 2018
Using GeoJSON from an ESRI REST Service in Leaflet
I love Leaflet for making web maps but sometimes linking Leaflet with external spatial data resources, particularly those from ESRI, is difficult at best and almost impossible at worst. Tools like ESRI-Leaflet (https://esri.github.io/esri-leaflet/) have been a life saver in most cases, particularly for using ESRI basemaps. However, recently, I needed to use a Web Feature Service from an ArcGIS REST service to display data in leaflet. It took a while and I thought I'd share the results.
Understanding spatial REST services endpoints
First, all RESTful services terminate in an 'endpoint'. That is the final URL to access a particular layer of spatial data. For example, here is the ESRI REST endpoint for the US National Weather Service's Watches and Warnings data.
https://idpgis.ncep.noaa.gov/arcgis/rest/services/NWS_Forecasts_Guidance_Warnings/watch_warn_adv/MapServer/1
Depending on their configuration, ArcGIS Server-based REST layers can expose a 'query' interface. If available, it's linked on the bottom of the endpoint bottom. Look for this text:
Supported Operations: Query Generate Renderer Return Update
Clicking the Query page will bring you to an intimidating Query form. However, the form itself can be bypassed using an HTTP POST.
https://idpgis.ncep.noaa.gov/arcgis/rest/services/NWS_Forecasts_Guidance_Warnings/watch_warn_adv/MapServer/1/query?where=phenom%3D%27FW%27&outFields=*&f=geojson
Basically, you call the query endpoint and pass a 'where' clause (in this case it's: where=phenom='FW'). The URL will get mangled to replace the = (%3D) and ' (%27) but basically calling with a where clause and passing it an outFields=* will give you a filtered set of elements and all their data fields. Finally, including the "f=geojson" will return the results in geojson format.
Getting GeoJSON from the REST service into Leaflet
In leaflet, just define a variable to to that url something like:
myURL = "https://idpgis.ncep.noaa.gov/arcgis/rest/services/NWS_Forecasts_Guidance_Warnings/watch_warn_adv/MapServer/1/query?where=phenom%3D%27FW%27&outFields=*&f=geojson";
The layer itself is loaded using JQueries AJAX functionality as follow:
var geojsonLayer;
$.ajax({
dataType: "json",
url: myURL,
success: function(data) {
geojsonLayer = new L.GeoJSON(data,{style: style}).addTo(map);}
}).error(function() {});
function style() {
return {
weight: 1,opacity: 0.65,dashArray: '1',fillOpacity: 0.65,color: '#000000',fillColor: '#d53e4f'
};
}
This will call the style() function for each GeoJSON element loaded and then add the result to a Leaflet map called 'map'.
Then you can add and use the geojsonLayer as needed within Leaflet. There are lots of other things you can do with that Layer, like zoom on click, highlighting, etc.., and those are well described in the Leaflet Chloropleth tutorial here: https://leafletjs.com/examples/choropleth/
Subscribe to:
Posts (Atom)