Accessing ArcGIS REST services using R

5898
3
03-17-2019 09:34 AM
Egge-Jan_Pollé
MVP Regular Contributor
3 3 5,898

In this post we will demonstrate how you - as a Spatial Data Scientist - can use R to access an ArcGIS REST Service, by answering the following question: "Are there any abandoned railroads in Florida?".

The ArcGIS Living Atlas of the World offers a nice data set with railroads in the United States: USA Railroads. Following the Service URL we can get to the query page of this Feature Layer.

The R script below shows how you can quickly create an interactive map to answer our question. Please scroll down for a little explanation...

library(httr)
library(sf)
library(tmap)

url <- parse_url("https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services")
url$path <- paste(url$path, "USA_Railroads_1/FeatureServer/0/query", sep = "/")
url$query <- list(where = "STATE = 'FL'",
                  outFields = "*",
                  returnGeometry = "true",
                  f = "geojson")
request <- build_url(url)

Florida_Railroads <- st_read(request)

tmap_mode(mode = "view")
tm_shape(Florida_Railroads)+tm_lines(col="NET_DESC", palette = "Set1", lwd = 5)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

In RStudio we start by loading the 3 following R packages:

  • httr - to help us build the query URL
  • sf - to read the spatial data
  • tmap - to create the interactive map, based on the Leaflet JavaScript library

We parse the URL to create a list where we can add all the parameters of our query - where, outFields, returnGeometry and f - with their appropriate values. As soon as the list is populated we use the function build_url() to create a properly encoded request. This request is the passed to the function st_read() to populate Florida_Railroads. This Florida_Railroads becomes both a simple features object and a data frame, i.e. it does contain both the geometry and the attribute values of the railroads.

In the screen dump below we can see that the total number of records returned is 3305, which is well beyond the maxRecordCount (1000) for this Feature Layer. The GDAL library, which is used by the st_read() function in the sf package, provides automatic paging. Nice, isn't it?

With the last two lines in the script we create the interactive map in the Viewer in RStudio.

So, the answer to our question is: "Yes, there are quite a few abandoned railroads in Florida". These abandoned lines are marked in red in the map in the screen dump below.

3 Comments
About the Author
GIS Consultant at Avineon-Tensing