| Title: | R-ArcGIS Bridge Utility Functions |
| Version: | 0.4.0 |
| Description: | Developer oriented utility functions designed to be used as the building blocks of R packages that work with ArcGIS Location Services. It provides functionality for authorization, Esri JSON construction and parsing, as well as other utilities pertaining to geometry and Esri type conversions. To support 'ArcGIS Pro' users, authorization can be done via 'arcgisbinding'. Installation instructions for 'arcgisbinding' can be found at https://developers.arcgis.com/r-bridge/installation/. |
| License: | Apache License (≥ 2) |
| URL: | https://github.com/R-ArcGIS/arcgisutils, https://developers.arcgis.com/r-bridge/api-reference/arcgisutils/ |
| BugReports: | https://github.com/R-ArcGIS/arcgisutils/issues |
| Depends: | R (≥ 4.2) |
| Imports: | cli, httr2 (≥ 1.0.5), R6, RcppSimdJson, rlang, S7, sf, utils, yyjsonr, lifecycle |
| Suggests: | arcgisbinding, collapse (≥ 2.0.0), data.table, jsonify, testthat (≥ 3.0.0), curl, vctrs |
| Config/rextendr/version: | 0.4.2 |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Language: | en |
| RoxygenNote: | 7.3.2 |
| SystemRequirements: | Cargo (Rust's package manager), rustc >= 1.67, xz |
| NeedsCompilation: | yes |
| Packaged: | 2025-09-17 19:20:32 UTC; josiahparry |
| Author: | Josiah Parry |
| Maintainer: | Josiah Parry <josiah.parry@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-09-18 05:10:35 UTC |
Set user-agent for arcgisutils
Description
Override the default user-agent set by httr2 to indicate that a request came from arcgisutils.
Usage
arc_agent(req)
Arguments
req |
an httr2 request |
Value
an httr2 request object
Examples
req <- httr2::request("http://example.com")
arc_agent(req)
Generate base request
Description
This function takes a url and creates a basic httr2 request that
adds the user-agent and adds an authorization token to the
X-Esri-Authorization header.
Usage
arc_base_req(
url,
token = NULL,
path = NULL,
query = NULL,
error_call = rlang::caller_env()
)
Arguments
url |
a valid url that is passed to |
token |
an object of class |
path |
a character vector of paths to be appended to url using |
query |
a named vector or named list of query parameters to be appended to the url using |
error_call |
the caller environment to be used when propagating errors. |
Value
an httr2_request with the X-Esri-Authorization header and User-Agent set.
Examples
arc_base_req("https://arcgis.com")
Form request parameters
Description
ArcGIS endpoints make extensive use of form encoded data for the body of http requests. Form requests require that each element has a name and is encoded as a single string—often as json.
Usage
arc_form_params(params = list())
as_form_params(x)
Arguments
params |
a named list with scalar character elements |
x |
for |
Details
The arc_form_params class provides validation of form body parameters
ensuring that each element is a scalar string. It uses a named list
internally to store the parameters.
The helper function as_form_params() converts a named list to form
parameters by automatically JSON-encoding each element using
yyjsonr::write_json_str() with auto_unbox = TRUE.
Value
an object of class arc_form_params
See Also
Other geoprocessing:
arc_gp_job,
arc_job_status(),
gp_params
Other geoprocessing:
arc_gp_job,
arc_job_status(),
gp_params
Examples
arc_form_params(
list(f = "json", outFields = "*", where = "1 = 1")
)
Create a Geoprocessing Service Job
Description
The arc_gp_job class is used to interact with Geoprocessing Services in
ArcGIS Online and Enterprise.
Usage
new_gp_job(base_url, params = list(), token = arc_token())
Arguments
base_url |
the URL of the job service (without |
params |
a named list where each element is a scalar character |
token |
default |
Details
The arc_gp_job uses S7 classes for the job request parameters and job status
via arc_form_params() and arc_job_status() respectively. Importantly,
arc_form_params() ensures that parameters provided to a geoprocessing
service are all character scalars as required by the form body.
Value
An object of class arc_gp_job.
Public fields
base_urlthe URL of the job service (without
/submitJob)idthe ID of the started job.
NULLself$start()has not been called.
Active bindings
paramsreturns an S7 object of class
arc_form_params(seearc_form_params()) the list can be accessed viaself$params@params.statusreturns the status of the geoprocessing job as an S7 object of class
gp_job_status(seearc_job_status()) by querying the/jobs/{job-id}endpoint.resultsreturns the current results of the job by querying the
/jobs/{job-id}/resultsendpoint.
Methods
Public methods
Method new()
Usage
arc_gp_job$new( base_url, params = list(), result_fn = NULL, token = arc_token(), error_call = rlang::caller_call() )
Arguments
base_urlthe URL of the job service (without
/submitJob)paramsa named list where each element is a scalar character
result_fnDefault
NULL. An optional function to apply to the results JSON. By default parses results usingRcppSimdJson::fparse().tokendefault
arc_token(). The token to be used with the job.error_calldefault
rlang::caller_call()the calling environment.
Method start()
Starts the job by calling the /submitJob endpoint. This also sets the public field id.
Usage
arc_gp_job$start()
Method cancel()
Cancels a job by calling the /cancel endpoint.
Usage
arc_gp_job$cancel()
Method await()
Waits for job completion and returns results.
Usage
arc_gp_job$await(interval = 0.1, verbose = FALSE)
Arguments
intervalpolling interval in seconds (default 0.1)
verbosewhether to print status messages (default FALSE)
Method clone()
The objects of this class are cloneable with this method.
Usage
arc_gp_job$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
Other geoprocessing:
arc_form_params(),
arc_job_status(),
gp_params
Examples
url <- paste0(
"https://logistics.arcgis.com/arcgis/",
"rest/services/World/ServiceAreas/",
"GPServer/GenerateServiceAreas"
)
job <- new_gp_job(url, list(f = "json"))
job
# extract params S7 class
params <- job$params
params
# view underlying list
params@params
Fetch Group Information
Description
Fetches metadata about a group based on a provided group_id.
Usage
arc_group(group_id, host = arc_host(), token = arc_token())
Arguments
group_id |
the unique group identifier. A scalar character. |
host |
default |
token |
an |
Details
Value
a list with group metadata
See Also
Other portal organization:
arc_user()
Examples
arc_group("2f0ec8cb03574128bd673cefab106f39")
Determines Portal Host
Description
Returns a scalar character indicating the host to make requests to.
Usage
arc_host()
Details
By default, the host is ArcGIS Online <https://www.arcgis.com>. If the
environment variable ARCGIS_HOST is set, it will be returned.
Value
A scalar character, "https://www.arcgis.com" by default.
Examples
arc_host()
Portal Item Metadata
Description
Given the unique ID of a content item, fetches the item's metadata from a portal.
Usage
arc_item(item_id, host = arc_host(), token = arc_token())
Arguments
item_id |
the ID of the item to fetch. A scalar character. |
host |
default |
token |
an |
Details
See API Reference for more information.
Value
an object of class PortalItem which is a list with the item's metadata.
See Also
Other portal item:
arc_item_data()
Examples
arc_item("9df5e769bfe8412b8de36a2e618c7672")
Download an Item's Data
Description
Download the data backing a portal item. This function always returns a raw vector as the type of the data that is downloaded cannot always be known.
Usage
arc_item_data(item, host = arc_host(), token = arc_token())
Arguments
item |
the item ID or the result of |
host |
default |
token |
an |
Details
Value
a raw vector containing the bytes of the data associated with the item. If the response is application/json then the json string is returned without parsing.
See Also
Other portal item:
arc_item()
Examples
arc_item_data("9df5e769bfe8412b8de36a2e618c7672")
Geoprocessing Job Status
Description
Represents the status of a geoprocessing job.
Usage
arc_job_status(status = character(0))
Arguments
status |
a scalar character. Must be one of |
Value
an object of class arc_job_status
See Also
Other geoprocessing:
arc_form_params(),
arc_gp_job,
gp_params
Examples
arc_job_status("esriJobSubmitted")
Paginate ArcGIS Requests
Description
Many API endpoints provide common pagination properties. arc_paginate_request() automatically applies pagination to an input request.
Usage
arc_paginate_req(req, page_size = 10, max_pages = Inf, .progress = TRUE)
Arguments
req |
an |
page_size |
a scalar integer between 1 and 100 indicating the number of responses per page. |
max_pages |
the maximum number of pages to fetch. By default fetches all pages. |
.progress |
default |
Value
a list of httr2_response.
References
See Also
Portal File Resources
Description
The resources endpoint lists all file resources for the organization.
Usage
arc_portal_resources(
id = arc_portal_self(token)[["id"]],
page_size = 50,
max_pages = Inf,
.progress = TRUE,
host = arc_host(),
token = arc_token()
)
Arguments
id |
the portal ID. By default it fetches the |
page_size |
a scalar integer between 1 and 100 indicating the number of responses per page. |
max_pages |
the maximum number of pages to fetch. By default fetches all pages. |
.progress |
default |
host |
default |
token |
an object of class |
Value
a data.frame of resources available to your portal.
References
See Also
Other portal:
arc_portal_urls(),
arc_portal_users(),
self
Examples
## Not run:
set_arc_token(auth_user())
arc_portal_resources()
## End(Not run)
List ArcGIS Enterprise Servers
Description
The servers resource lists the ArcGIS Server sites that have been federated with the portal.
Usage
arc_portal_servers(
id = arc_portal_self(token)[["id"]],
host = arc_host(),
token = arc_token()
)
Arguments
id |
the portal ID. By default it fetches the |
host |
default |
token |
an object of class |
Value
a data.frame of servers
Examples
## Not run:
set_arc_token(auth_user())
arc_portal_servers()
## End(Not run)
Organization's URLs
Description
Returns the URLs of an organizations services.
Usage
arc_portal_urls(host = arc_host(), token = arc_token())
Arguments
host |
default |
token |
an |
Details
See API Reference for more information.
Value
a data.frame
See Also
Other portal:
arc_portal_resources(),
arc_portal_users(),
self
Examples
arc_portal_urls()
Portal Users
Description
This function lists all users in a portal.
Usage
arc_portal_users(
id = arc_portal_self(token)[["id"]],
sort_field = NULL,
provider = NULL,
sort_order = NULL,
role = NULL,
fullname = NULL,
username = NULL,
firstname = NULL,
lastname = NULL,
filter_intersection = NULL,
page_size = 50,
max_pages = Inf,
.progress = TRUE,
host = arc_host(),
token = arc_token()
)
Arguments
id |
the portal ID. By default it fetches the |
sort_field |
optional field to sort by. It must be one of "username", "fullname", "created", "lastlogin", "mfaenabled", "level", "role". |
provider |
optional filter users based on their identity provider. Must be one of "arcgis", "enterprise", "facebook", "google", "apple", or "github". |
sort_order |
optional order to sort by. It must be one of |
role |
optional role to filter down to. It must be one of "org_admin", "org_publisher", "org_user". |
fullname |
optional string of the user's fullanme to search for. |
username |
optional string of the user's user name to search for. |
firstname |
optional string of the user's first name to search for. |
lastname |
optional string of the user's last name to search for. |
filter_intersection |
optional boolean value. If |
page_size |
a scalar integer between 1 and 100 indicating the number of responses per page. |
max_pages |
the maximum number of pages to fetch. By default fetches all pages. |
.progress |
default |
host |
default |
token |
an object of class |
Value
a data.frame of users.
References
See Also
Other portal:
arc_portal_resources(),
arc_portal_urls(),
self
Examples
## Not run:
set_arc_token(auth_user())
arc_portal_users()
## End(Not run)
Manage authorization tokens
Description
These functions are used to set, fetch, and check authorization tokens.
Usage
arc_token(token = "ARCGIS_TOKEN")
set_arc_token(token, ...)
unset_arc_token(token = NULL)
obj_check_token(token, call = rlang::caller_env())
check_token_has_user(token, call = rlang::caller_env())
Arguments
token |
for |
... |
named arguments to set |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Details
It is possible to have multiple authorization tokens in one session. These functions assist you in managing them.
arc_token() is used to fetch tokens by name. The default token is ARCGIS_TOKEN.
However, they can be any valid character scalar. set_arc_token() will create
store a token with the name ARCGIS_TOKEN. However, you can alternatively
set the tokens by name using a key-value pair. The key is what you would pass
to arc_token() to fetch the httr2_token object. To remove a token that has
been set, use unset_arc_token().
obj_check_token() is a developer oriented function that can be used to check
if an object is indeed an httr2_token. To check if a token has expired,
validate_or_refresh_token() will do so.
check_token_has_user() is a developer oriented function that checks to see
if a token has a username field associated with it.
For developers:
set_arc_token() uses a package level environment to store the tokens. The
tokens are fetched from the environment using arc_token().
Examples
# create fake tokens
token_a <- httr2::oauth_token("1234", arcgis_host = arc_host())
token_b <- httr2::oauth_token("abcd", arcgis_host = arc_host())
# set token to the default location
set_arc_token(token_a)
# fetch token from the default location
arc_token()
# set token by name
set_arc_token(org_a = token_a, org_b = token_b)
# fetch token by name
arc_token("org_a")
arc_token("org_b")
# unset tokens
unset_arc_token()
unset_arc_token(c("org_a", "org_b"))
User Information
Description
Fetch a user's metadata based on username.
Usage
arc_user(username, host = arc_host(), token = arc_token())
Arguments
username |
the username to fetch. A scalar character. |
host |
default |
token |
an |
Details
Value
a list of class PortalUser
See Also
Other portal organization:
arc_group()
Examples
arc_user("esri_en")
Discover Authenticated User Metadata
Description
Given an authentication token, return a list of user-specfic information such as the user ID, username, available credits, email, groups, last login date and more.
Usage
arc_user_self(
host = arc_host(),
token = arc_token(),
error_call = rlang::caller_call()
)
Arguments
host |
default |
token |
an |
error_call |
the caller environment to be used when propagating errors. |
Value
a list of the authenticated user's metadata
References
Examples
## Not run:
if (interactive()) {
arc_user_self(token = auth_user())
}
## End(Not run)
Create Esri JSON Geometry Objects
Description
as_esri_geometry() converts an sfg object to a EsriJSON Geometry object as a string.
Usage
as_esri_geometry(x, crs = NULL, call = rlang::caller_env())
Arguments
x |
an object of class |
crs |
the coordinate reference system. It must be interpretable by |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Details
See as_featureset() and as_features() for converting sfc and sf objects into EsriJSON.
Value
a scalar string
References
Examples
library(sf)
# POINT
# create sfg points
xy <- st_point(c(1, 2))
xyz <- st_point(c(1, 2, 3))
xym <- st_point(c(1, 2, 3), dim = "XYM")
xyzm <- st_point(c(1, 2, 3, 4))
as_esri_geometry(xy)
as_esri_geometry(xyz)
as_esri_geometry(xym)
as_esri_geometry(xyzm)
# MULTIPOINT
# vector to create matrix points
set.seed(0)
x <- rnorm(12)
xy <- st_multipoint(matrix(x, ncol = 2))
xyz <- st_multipoint(matrix(x, ncol = 3))
xym <- st_multipoint(matrix(x, ncol = 3), dim = "XYM")
xyzm <- st_multipoint(matrix(x, ncol = 4), dim = "XYM")
as_esri_geometry(xy)
as_esri_geometry(xyz)
as_esri_geometry(xym)
as_esri_geometry(xyzm)
# LINESTRING
xy <- st_linestring(matrix(x, ncol = 2))
xyz <- st_linestring(matrix(x, ncol = 3))
xym <- st_linestring(matrix(x, ncol = 3), dim = "XYM")
xyzm <- st_linestring(matrix(x, ncol = 4), dim = "XYM")
as_esri_geometry(xy)
as_esri_geometry(xyz)
as_esri_geometry(xym)
as_esri_geometry(xyzm)
# MULTILINESTRING
as_esri_geometry(st_multilinestring(list(xy, xy)))
as_esri_geometry(st_multilinestring(list(xyz, xyz)))
as_esri_geometry(st_multilinestring(list(xym, xym)))
as_esri_geometry(st_multilinestring(list(xyzm, xyzm)))
# POLYGON
coords <- rbind(
c(0, 0, 0, 1),
c(0, 1, 0, 1),
c(1, 1, 1, 1),
c(1, 0, 1, 1),
c(0, 0, 0, 1)
)
xy <- st_polygon(list(coords[, 1:2]))
xyz <- st_polygon(list(coords[, 1:3]))
xym <- st_polygon(list(coords[, 1:3]), dim = "XYM")
xyzm <- st_polygon(list(coords))
as_esri_geometry(xy)
as_esri_geometry(xyz)
as_esri_geometry(xym)
as_esri_geometry(xyzm)
# MULTIPOLYGON
as_esri_geometry(st_multipolygon(list(xy, xy)))
as_esri_geometry(st_multipolygon(list(xyz, xyz)))
as_esri_geometry(st_multipolygon(list(xym, xym)))
as_esri_geometry(st_multipolygon(list(xyzm, xyzm)))
Convert an object to an extent
Description
Given an sf or sfc object create a list that represents the extent of the
object. The result of this function can be parsed directly into json using
jsonify::to_json(x, unbox = TRUE) or included into a list as the extent
component that will be eventually converted into json using the above function.
Usage
as_extent(x, crs = sf::st_crs(x), call = rlang::caller_env())
Arguments
x |
an sf or sfc object |
crs |
the CRS of the object. Must be parsable by |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Value
An extent json object. Use jsonify::to_json(x, unbox = TRUE) to convert
to json.
Examples
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
as_extent(nc)
Create Esri Features
Description
These functions create an array of Esri Feature objects.
Each feature consists of a geometry and attribute field.
The result of as_esri_features() is a JSON array of Features whereas
as_features() is a list that represents the same JSON array. Using
jsonify::to_json(as_features(x), unbox = TRUE) will result in the same
JSON array.
Usage
as_features(x, crs = sf::st_crs(x), call = rlang::caller_env())
as_esri_features(x, crs = sf::st_crs(x), call = rlang::caller_env())
Arguments
x |
an object of class |
crs |
the coordinate reference system. It must be interpretable by |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Value
Either a scalar string or a named list.
References
Examples
library(sf)
# POINT
# create sfg points
xy <- st_sfc(st_point(c(1, 2)))
xyz <- st_sfc(st_point(c(1, 2, 3)))
xym <- st_sfc(st_point(c(1, 2, 3), dim = "XYM"))
as_esri_features(xy)
as_esri_features(xyz)
as_esri_features(xym)
# MULTIPOINT
# vector to create matrix points
set.seed(0)
x <- rnorm(12)
xy <- st_sfc(st_multipoint(matrix(x, ncol = 2)))
xyz <- st_sfc(st_multipoint(matrix(x, ncol = 3)))
xym <- st_sfc(st_multipoint(matrix(x, ncol = 3), dim = "XYM"))
as_esri_features(xy)
as_esri_features(xyz)
as_esri_features(xym)
# LINESTRING
xy <- st_sfc(st_linestring(matrix(x, ncol = 2)))
xyz <- st_sfc(st_linestring(matrix(x, ncol = 3)))
xym <- st_sfc(st_linestring(matrix(x, ncol = 3), dim = "XYM"))
as_esri_features(xy)
as_esri_features(xyz)
as_esri_features(xym)
# MULTILINESTRING
as_esri_features(st_sfc(st_multilinestring(list(xy[[1]], xy[[1]]))))
as_esri_features(st_sfc(st_multilinestring(list(xyz[[1]], xyz[[1]]))))
as_esri_features(st_sfc(st_multilinestring(list(xym[[1]], xym[[1]]))))
# POLYGON
coords <- rbind(
c(0, 0, 0, 1),
c(0, 1, 0, 1),
c(1, 1, 1, 1),
c(1, 0, 1, 1),
c(0, 0, 0, 1)
)
xy <- st_sfc(st_polygon(list(coords[, 1:2])))
xyz <- st_sfc(st_polygon(list(coords[, 1:3])))
xym <- st_sfc(st_polygon(list(coords[, 1:3]), dim = "XYM"))
as_esri_features(xy)
as_esri_features(xyz)
as_esri_features(xym)
# MULTIPOLYGON
as_esri_features(st_sfc(st_multipolygon(list(xy[[1]], xy[[1]]))))
as_esri_features(st_sfc(st_multipolygon(list(xyz[[1]], xyz[[1]]))))
as_esri_features(st_sfc(st_multipolygon(list(xym[[1]], xym[[1]]))))
Create Esri FeatureSet Objects
Description
These functions create an Esri FeatureSet object. A FeatureSet contains an inner array of features as well as additional metadata about the the collection such as the geometry type, spatial reference, and object ID field.
Usage
as_featureset(x, crs = sf::st_crs(x), call = rlang::caller_env())
as_esri_featureset(x, crs = sf::st_crs(x), call = rlang::caller_env())
Arguments
x |
an object of class |
crs |
the coordinate reference system. It must be interpretable by |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Value
a list or a json string
References
Examples
library(sf)
# POINT
# create sfg points
xy <- st_sfc(st_point(c(1, 2)))
xyz <- st_sfc(st_point(c(1, 2, 3)))
xym <- st_sfc(st_point(c(1, 2, 3), dim = "XYM"))
as_esri_featureset(xy)
as_esri_featureset(xyz)
as_esri_featureset(xym)
# MULTIPOINT
# vector to create matrix points
set.seed(0)
x <- rnorm(12)
xy <- st_sfc(st_multipoint(matrix(x, ncol = 2)))
xyz <- st_sfc(st_multipoint(matrix(x, ncol = 3)))
xym <- st_sfc(st_multipoint(matrix(x, ncol = 3), dim = "XYM"))
as_esri_featureset(xy)
as_esri_featureset(xyz)
as_esri_featureset(xym)
# LINESTRING
xy <- st_sfc(st_linestring(matrix(x, ncol = 2)))
xyz <- st_sfc(st_linestring(matrix(x, ncol = 3)))
xym <- st_sfc(st_linestring(matrix(x, ncol = 3), dim = "XYM"))
as_esri_featureset(xy)
as_esri_featureset(xyz)
as_esri_featureset(xym)
# MULTILINESTRING
as_esri_featureset(st_sfc(st_multilinestring(list(xy[[1]], xy[[1]]))))
as_esri_featureset(st_sfc(st_multilinestring(list(xyz[[1]], xyz[[1]]))))
as_esri_featureset(st_sfc(st_multilinestring(list(xym[[1]], xym[[1]]))))
# POLYGON
coords <- rbind(
c(0, 0, 0, 1),
c(0, 1, 0, 1),
c(1, 1, 1, 1),
c(1, 0, 1, 1),
c(0, 0, 0, 1)
)
xy <- st_sfc(st_polygon(list(coords[, 1:2])))
xyz <- st_sfc(st_polygon(list(coords[, 1:3])))
xym <- st_sfc(st_polygon(list(coords[, 1:3]), dim = "XYM"))
as_esri_featureset(xy)
as_esri_featureset(xyz)
as_esri_featureset(xym)
# MULTIPOLYGON
as_esri_featureset(st_sfc(st_multipolygon(list(xy[[1]], xy[[1]]))))
as_esri_featureset(st_sfc(st_multipolygon(list(xyz[[1]], xyz[[1]]))))
as_esri_featureset(st_sfc(st_multipolygon(list(xym[[1]], xym[[1]]))))
Esri Field Type Mapping
Description
Infers Esri field types from R objects. Use as_fields() to create a
data.frame of valid Esri Field Types
from an sf object or data.frame.
Usage
as_fields(.data, arg = rlang::caller_arg(.data), call = rlang::caller_env())
infer_esri_type(
.data,
arg = rlang::caller_arg(.data),
call = rlang::caller_env()
)
fields_as_ptype_df(fields, n = 0, call = rlang::caller_env())
ptype_tbl(fields, n = 0, call = rlang::caller_env())
Arguments
.data |
an object of class |
arg |
An argument name in the current function. |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
fields |
a list or data.frame of field types. Requires the fields |
n |
the number of rows to create in the prototype table |
Details
-
as_fields()takes a data frame-like object and infers the Esri field type from it. -
fields_as_pytpe_df()takes a list withtypeandnameand creates an emptydata.framewith the corresponding column names and types. -
get_ptype()takes a scalar character containing the Esri field type and returns a prototype of the pertinent R type
Field type mapping:
Esri field types are mapped as
-
esriFieldTypeSmallInteger: integer -
esriFieldTypeSingle: double -
esriFieldTypeGUID: integer -
esriFieldTypeOID: integer -
esriFieldTypeInteger: integer -
esriFieldTypeBigInteger: double -
esriFieldTypeDouble: double -
esriFieldTypeString: character -
esriFieldTypeDate: date
R types are mapped as
-
double: esriFieldTypeDouble -
integer: esriFieldTypeInteger -
character: esriFieldTypeString -
date: esriFieldTypeDate -
raw: esriFieldTypeBlob
Value
-
fields_as_ptype_df()takes adata.framewith columnsnameandtypeand creates an emptydata.framewith the corresponding columns and R types -
as_fields()returns adata.framewith columnsname,type,alias,nullable, andeditablecolumnsThis resembles that of the
fieldsreturned by a FeatureService
Examples
inferred <- as_fields(iris)
inferred
fields_as_ptype_df(inferred)
Create Esri layer objects
Description
These functions are used to generate list objects that can be converted into json objects that are used in REST API requests. Notably they are used for adding R objects as items to a portal.
Usage
as_layer(
x,
name,
title,
layer_definition = as_layer_definition(x, name, "object_id", infer_esri_type(x)),
id = NULL,
layer_url = NULL,
legend_url = NULL,
popup_info = NULL,
call = rlang::caller_env()
)
as_layer_definition(
x,
name,
object_id_field,
fields = infer_esri_type(x),
display_field = NULL,
drawing_info = NULL,
has_attachments = FALSE,
max_scale = 0,
min_scale = 0,
templates = NULL,
type_id_field = NULL,
types = NULL,
call = rlang::caller_env()
)
as_feature_collection(
layers = list(),
show_legend = TRUE,
call = rlang::caller_env()
)
Arguments
x |
an object of class |
name |
a scalar character of the name of the layer. Must be unique. |
title |
A user-friendly string title for the layer that can be used in a table of contents. |
layer_definition |
a layer definition list as created by |
id |
A number indicating the index position of the layer in the WMS or map service. |
layer_url |
default |
legend_url |
default |
popup_info |
default |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
object_id_field |
a scalar character vector indicating the name of the object ID field in the dataset. |
fields |
a data.frame describing the fields in |
display_field |
default |
drawing_info |
default |
has_attachments |
default |
max_scale |
default |
min_scale |
default |
templates |
default |
type_id_field |
default |
types |
An array of type objects available for the dataset.
This is used when the |
layers |
a list of layers as created by |
show_legend |
default |
Details
A featureCollection defines a layer of features that will be stored on a web map.
It consists of an array of layers. The layer contains the features
(attributes and geometries) as a featureSet (see as_esri_featureset()) and
additional metadata which is stored in the layerDefinitionobject. The
layerDefinition most importantly documents the fields in the object, the object ID,
and additional metadata such as name, title, and display scale.
Additional documentation for these json object:
Value
A list object containing the required fields for each respective json type.
The results can be converted to json using jsonify::to_json(x, unbox = TRUE)
Examples
ld <- as_layer_definition(iris, "iris", "objectID")
l <- as_layer(iris, "iris name", "Iris Title")
fc <- as_feature_collection(layers = list(l))
Authorization
Description
Authorize your R session to connect to an ArcGIS Portal. See details.
Usage
auth_code(client = Sys.getenv("ARCGIS_CLIENT"), host = arc_host())
auth_client(
client = Sys.getenv("ARCGIS_CLIENT"),
secret = Sys.getenv("ARCGIS_SECRET"),
host = arc_host(),
expiration = 120
)
auth_binding()
auth_user(
username = Sys.getenv("ARCGIS_USER"),
password = Sys.getenv("ARCGIS_PASSWORD"),
host = arc_host(),
expiration = 60
)
auth_key(api_key = Sys.getenv("ARCGIS_API_KEY"), host = arc_host())
refresh_token(token, client = Sys.getenv("ARCGIS_CLIENT"), host = arc_host())
validate_or_refresh_token(
token,
client = Sys.getenv("ARCGIS_CLIENT"),
host = arc_host(),
refresh_threshold = 10,
call = rlang::caller_env()
)
Arguments
client |
an OAuth 2.0 developer application client ID. By default uses the
environment variable |
host |
default |
secret |
an OAuth 2.0 developer application secret. By default uses the environment
variable |
expiration |
the duration of the token in minutes. |
username |
default |
password |
default |
api_key |
default |
token |
an |
refresh_threshold |
default |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Details
ArcGIS Online and Enterprise Portals utilize OAuth2 authorization via their REST APIs.
-
auth_code()is the recommend OAuth2 workflow for interactive sessions -
auth_client()is the recommended OAuth2 workflow for non-interactive sessions -
auth_user()uses legacy username and password authorization using thegenerateTokenendpoint. It is only recommended for legacy systems that do not implement OAuth2. -
auth_binding()fetches a token from the active portal set byarcgisbinding. Usesarcgisbinding::arc.check_portal()to extract the authorization token. Recommended if using arcgisbinding.
Value
an httr2_token
Examples
## Not run:
auth_code()
auth_client()
auth_user()
auth_key()
auth_binding()
## End(Not run)
General utility functions
Description
General utility functions
Usage
compact(.x)
a %||% b
check_dots_named(dots, call = rlang::caller_env())
data_frame(x, call = rlang::caller_call())
Arguments
.x |
a list |
a |
an R object |
b |
an R object |
dots |
a list collected from dots via |
call |
default |
x |
a data.frame |
Details
-
compact()removes anyNULLlist elements -
%||%is a special pipe operator that returnsbifaisNULL
Value
-
compact()a list -
%||%the first non-null item orNULLif both areNULL
Examples
# remove null elements
compact(list(a = NULL, b = 1))
# if NULL return rhs
NULL %||% 123
# if not NULL return lhs
123 %||% NULL
Portal Content Items
Description
For a given user or group, returns a data.frame of all content items owned by them.
Usage
arc_group_content(group, host = arc_host(), token = arc_token())
arc_user_content(user, host = arc_host(), token = arc_token())
Arguments
group |
a scalar character of the group ID or a |
host |
default |
token |
an |
user |
a scalar character of the username or a |
Value
a data.frame of content item metadata
References
Examples
## Not run:
library(arcgis)
# authenticate
set_arc_token(auth_user())
# get your own content items
self <- arc_user_self()
arc_user_content(self$username)
# get a specific group's items
arc_group_content("2f0ec8cb03574128bd673cefab106f39")
## End(Not run)
Detect errors in parsed json response
Description
The requests responses from ArcGIS don't return the status code in the response itself but rather from the body in the json. This function checks for the existence of an error. If an error is found, the contents of the error message are bubbled up.
Usage
detect_errors(response, error_call = rlang::caller_env())
catch_error(response, error_call = rlang::caller_env())
Arguments
response |
for |
error_call |
default |
Value
Nothing. Used for it's side effect. If an error code is encountered in the response an error is thrown with the error code and the error message.
Examples
## Not run:
response <- list(
error = list(
code = 400L,
message = "Unable to generate token.",
details = "Invalid username or password."
)
)
detect_errors(response)
## End(Not run)
Determine the dimensions of a geometry object
Description
Given an sfc or sfg object determine what dimensions are represented.
Usage
determine_dims(x)
has_m(x)
has_z(x)
Arguments
x |
an object of class |
Value
determine_dims() returns a scalar character of the value "xy", "xyz", or "xyzm" depending
on what dimensions are represented.
has_m() and has_z() returns a logical scalar of TRUE or FALSE if the
geometry has a Z or M dimension.
Examples
geo <- sf::st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)[["geometry"]]
determine_dims(geo)
has_z(geo)
has_m(geo)
Determine Esri Geometry type
Description
Takes an sf or sfc object and returns the appropriate Esri geometry type.
Usage
determine_esri_geo_type(x, call = rlang::caller_env())
Arguments
x |
an object of class |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Details
Geometry type mapping
-
POINT:esriGeometryPoint -
MULTIPOINT:esriGeometryMultipoint -
LINESTRING:esriGeometryPolyline -
MULTILINESTRING:esriGeometryPolyline -
POLYGON:esriGeometryPolygon -
MULTIPOLYGON:esriGeometryPolygon
Value
returns a character scalar of the corresponding Esri geometry type
Examples
determine_esri_geo_type(sf::st_point(c(0, 0)))
Retrieve metadata
Description
Utility functions for feature service metadata.
Usage
fetch_layer_metadata(url, token = NULL, call = rlang::caller_env())
Arguments
url |
the url of the item. |
token |
an |
call |
default |
Details
-
fetch_layer_metadata()given a request, fetches the metadata by setting the query parameterf=json
Value
returns a list object
Examples
# url is broken into parts to fit within 100 characters to avoid CRAN notes
url_parts <- c(
"https://services.arcgis.com/P3ePLMYs2RVChkJx/ArcGIS/rest/services",
"/USA_Counties_Generalized_Boundaries/FeatureServer/0"
)
furl <- paste0(url_parts, collapse = "")
meta <- fetch_layer_metadata(furl)
head(names(meta))
Geoprocessing Parameter Types
Description
Functions for converting R objects to and from ArcGIS geoprocessing parameter types. These functions handle the serialization and parsing of various data types used in ArcGIS geoprocessing services.
Usage
parse_gp_feature_record_set(json)
as_gp_feature_record_set(x)
parse_gp_record_set(json)
as_record_set(x)
as_gp_raster_layer(x)
gp_linear_unit(distance = integer(0), units = character(0))
as_gp_linear_unit(x)
parse_gp_linear_unit(json)
gp_areal_unit(area = integer(0), units = character(0))
as_gp_areal_unit(x)
parse_gp_areal_unit(json)
as_gp_date(x)
parse_gp_date(json)
as_spatial_reference(x)
parse_spatial_reference(json)
Arguments
json |
raw json to parse |
x |
the object to convert into json |
distance |
a scalar number of the distance. |
units |
the unit of the measurement. Must be one of "esriUnknownAreaUnits", "esriSquareInches", "esriSquareFeet", "esriSquareYards", "esriAcres", "esriSquareMiles", "esriSquareMillimeters", "esriSquareCentimeters", "esriSquareDecimeters", "esriSquareMeters", "esriAres", "esriHectares", "esriSquareKilometers", "esriSquareInchesUS", "esriSquareFeetUS", "esriSquareYardsUS", "esriAcresUS", "esriSquareMilesUS". |
area |
a scalar number of the measurement. |
Details
This package provides support for the following geoprocessing parameter types:
Implemented Types
-
GPFeatureRecordSetLayer: Feature collections with geometry and attributes
-
GPRecordSet: Tabular data without geometry
-
GPRasterDataLayer: Raster datasets from Portal items, Image Servers, or URLs
-
GPLinearUnit: Linear distance measurements with units
-
GPArealUnit: Area measurements with units
-
GPDate: Date/time values in milliseconds since epoch
-
GPSpatialReference: Coordinate reference systems
Not Yet Implemented
The following types are planned for future implementation:
-
GPField: Field definitions with name, type, and properties
-
GPMultiValue: Arrays of values for a single data type
-
GPValueTable: Flexible table-like objects with rows and columns
-
GPComposite: Parameters that accept multiple data types
-
GPEnvelope: Bounding box extents (use
as_extent()for GPExtent)
Usage Patterns
Most functions follow a consistent pattern:
-
as_gp_*(): Convert R objects to geoprocessing parameter JSON -
parse_gp_*(): Parse geoprocessing response JSON to R objects Constructor functions (e.g.,
gp_linear_unit(),gp_areal_unit()) create typed S7 objects
Examples
# Create a linear unit distance <- gp_linear_unit(distance = 100, units = "esriMeters") # Convert spatial data to feature record set as_gp_feature_record_set(my_sf_data) # Parse a geoprocessing response parse_gp_feature_record_set(response_json)
References
See Also
Other geoprocessing:
arc_form_params(),
arc_gp_job,
arc_job_status()
Examples
# create a feature record set
fset <- as_gp_feature_record_set(iris[1,])
fset
# create fake gp feature record set to parse
fset_list <- list(
list(
dataType = "GPFeatureRecordSetLayer",
paramName = "example",
value = as_featureset(iris[1,])
)
)
# create the json
json <- yyjsonr::write_json_str(fset_list, auto_unbox = TRUE)
# parse the record set json
parse_gp_feature_record_set(json)
# linear units
lu <- gp_linear_unit(10, "esriMeters")
lu
as_gp_linear_unit(lu)
# areal units
au <- gp_areal_unit(10, "esriSquareMeters")
au
as_gp_areal_unit(au)
# dates
json <- r"({
"paramName": "Output_Date",
"dataType": "GPDate",
"value": 1199145600000
})"
parse_gp_date(json)
Date handling
Description
Esri date fields are represented as milliseconds from the Unix Epoch.
Usage
is_date(x, tz)
date_to_ms(x, tz = "UTC")
from_esri_date(x)
Arguments
x |
an object of class |
tz |
a character string. The time zone specification to be used
for the conversion, if one is required. System-specific (see
time zones), but |
Details
-
is_date(): checks if an object is aDateorPOSIXtclass object. -
date_to_ms()converts a date object to milliseconds from the Unix Epoch in the specified time zone.
Value
-
is_date()returns a logical scalar -
date_to_ms()returns a numeric vector of times in milliseconds from the Unix Epoch in the specified time zone.
Examples
today <- Sys.Date()
is_date(today)
date_to_ms(today)
Parse Esri JSON
Description
Parses an Esri FeatureSet JSON object into an R object. If there is no geometry present, a data.frame is returned. If there is geometry, an sf object is returned.
Usage
parse_esri_json(string, ..., call = rlang::caller_env())
Arguments
string |
the raw Esri JSON string. |
... |
additional arguments passed to |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Value
A data.frame. If geometry is found, returns an sf object.
Examples
esri_json <- '{
"geometryType": "esriGeometryPolygon",
"spatialReference": {
"wkid": 4326
},
"hasZ": false,
"hasM": false,
"features": [
{
"attributes": {
"id": 1
},
"geometry": {
"rings": [
[
[0.0, 0.0],
[1.0, 0.0],
[1.0, 1.0],
[0.0, 1.0],
[0.0, 0.0]
]
]
}
}
]
}'
parse_esri_json(esri_json)
Portal Item Types
Description
Every portal item has an associated item type. Each of those item types have keywords which cna be used to help narrow down search further.
Usage
item_type(item_type = character(0))
item_keyword(keyword = character(0))
portal_item_keywords()
portal_item_types()
Arguments
item_type |
a scalar character of the item type. See |
keyword |
a scalar character of the item type keyword. See |
References
Combine multiple data.frames
Description
A general function that takes a list of data.frames and returns a single
and combines them into a single object. It will use the fastest method
available. In order this is collapse::rowbind(), data.table::rbindlist(),
vctrs::list_unchop(), then do.call(rbind.data.frame, x).
Usage
rbind_results(x, call = rlang::current_env(), .ptype = data.frame())
Arguments
x |
a list where each element is a |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
.ptype |
currently unused. Reserved for a future release. |
Details
If all items in the list are data.frames, then the result will be a data.frame.
If all elements are an sf object, then the result will be an sf object.
If the items are mixed, the result will be a data.frame.
If any items are NULL, then an attribute null_elements will be attached
to the result. The attribute is an integer vector of the indices that
were NULL.
Value
see details.
Examples
x <- head(iris)
res <- rbind_results(list(x, NULL, x))
attr(res, "null_elements")
Search for Portal Items
Description
Perform full text search or use parameters to programamatically query your portal for content items.
Usage
search_items(
query = NULL,
filter = NULL,
title = NULL,
description = NULL,
snippet = NULL,
tags = NULL,
owner = NULL,
orgid = NULL,
item_type = NULL,
type_keywords = NULL,
created = NULL,
modified = NULL,
categories = NULL,
category_filters = NULL,
sort_field = NULL,
sort_order = NULL,
count_fields = NULL,
count_size = NULL,
display_sublayers = FALSE,
filter_logic = "and",
bbox = NULL,
page_size = 50,
max_pages = Inf,
.progress = TRUE,
host = arc_host(),
token = arc_token()
)
Arguments
query |
a scalar character for free text search or a valid query string as defined by the REST API. |
filter |
a scalar character. If provided all other arguments except query are ignored. |
title |
optional character vector of content item titles. |
description, snippet |
optional scalar character of text to check for. |
tags |
optional character vector of tags to search for. |
owner |
optional character vector of owner usernames to search for. |
orgid |
optional character vector of organization IDs to search for. |
item_type |
optional character vector of content item types. Validated with |
type_keywords |
optional character vector of content tpye keywords. Validated with |
created, modified |
optional length two vector which must be coercible to a date time vector. Converted using |
categories |
optional character vector of up to 8 organization content categories. |
category_filters |
optional character vector of up to 3 category terms. Items that have matching categories are returned. Exclusive with |
sort_field |
optional character vector of fields to sort by. Can sort by |
sort_order |
optional string. One of either |
count_fields |
optional character vector of up to 3 fields to count. Must be one of |
count_size |
optional integer determines the maximum number of field values to count for each counted field in |
display_sublayers |
default |
filter_logic |
default |
bbox |
unimplemented. |
page_size |
a scalar integer between 1 and 100 indicating the number of responses per page. |
max_pages |
the maximum number of pages to fetch. By default fetches all pages. |
.progress |
default |
host |
default |
token |
an object of class |
Details
Search is quite nuanced and should be handled with care as you may get unexpected results.
Most arguments are passed as
filterparameters to the API endpoint.If multiple values are passed to an argument such as
tags, the search will use an"OR"statement.When multiple arguments are provided, for example
tags,owner, anditem_type, the search will use"AND"logic—i.e. results shown match thetagsandowneranditem_type.Note: you can change this to
"OR"behavior by settingfilter_logic = "or"
If the
filterargument is provided, all other arguments exceptqueryare ignored.
Value
a data.frame.
References
Examples
crime_items <- search_items(
query = "crime",
item_type = "Feature Service",
max_pages = 1
)
crime_items
Access the Portal Self Resource
Description
The function returns the /self resource from the ArcGIS REST API. The /self endpoint
returns the view of the portal as seen by the current user, whether anonymous
or signed in.
Usage
arc_self_meta(token = arc_token(), error_call = rlang::current_call())
arc_portal_self(token = arc_token(), error_call = rlang::current_call())
Arguments
token |
an object of class |
error_call |
the caller environment to be used when propagating errors. |
Details
See the endpoint documentation for more details.
The Portal Self response can vary based on whether it's called by a user, an app, or both.
The response includes user and appinfo properties, and the variations in responses are primarily related to these two properties. As the names indicate, the user property includes information about the user making the call, and the appinfo property includes information pertaining to the app that made the call.
Value
A named list.
See Also
Other portal:
arc_portal_resources(),
arc_portal_urls(),
arc_portal_users()
Examples
## Not run:
set_arc_token(auth_code())
self <- arc_self_meta()
names(self)
## End(Not run)
Parse an ArcGIS service or content URL into its components
Description
arc_url_parse() uses httr2::url_parse() to parse URL components and
combine the components with a service or content URL type and a layer
number if applicable. A layer component is only included if the type is "MapServer" or
"FeatureServer" and the URL includes a trailing digit. A full url value is
also included in the returned list. The url, type, and layer components
are not part of the httr2_url class object returned by
httr2::url_parse().
Usage
arc_url_parse(url, base_url = NULL, error_call = rlang::caller_call())
arc_url_type(url, error_call = rlang::caller_call())
is_url(url, error_call = rlang::caller_call())
Arguments
url |
A string containing the URL to parse. |
base_url |
Use this as a parent, if |
error_call |
the caller environment to be used when propagating errors. |
Details
Value
A named list with the following components: scheme, hostname, username, password, port, path, query, fragment, url, type, and layer.
Examples
arc_url_parse(
"https://services.arcgisonline.com/arcgis/rest/services/USA_Topo_Maps/MapServer/0"
)
arc_url_parse(
"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"
)
arc_url_parse(
"https://services.arcgisonline.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"
)
Validate CRS object
Description
Takes a representation of a CRS and ensures that it is a valid one. The CRS
is validated using sf::st_crs() if it cannot be validated, a null CRS is returned.
Usage
validate_crs(crs, arg = rlang::caller_arg(crs), call = rlang::caller_env())
Arguments
crs |
a representation of a coordinate reference system. |
arg |
An argument name in the current function. |
call |
The execution environment of a currently running
function, e.g. You only need to supply Can also be For more information about error calls, see Including function calls in error messages. |
Details
See sf::st_crs() for more details on valid representations.
Value
Returns a list of length 1 with an element named spatialReference which is itself
a named list.
If the provided CRS returns a valid well-known ID (WKID) spatialReference contains
a named element called wkid which is the integer value of the WKID. If the WKID
is not known but the CRS returned is a valid well-known text representation the wkid field
is NA and another field wkt contains the valid wkt.
Examples
# using epsg code integer or string representation
validate_crs(3857)
validate_crs("EPSG:4326")
# using a custom proj4 string
proj4string <- "+proj=longlat +datum=WGS84 +no_defs"
crs <- validate_crs(proj4string)
# using wkt2 (from above result)
crs <- validate_crs(crs$spatialReference$wkt)