UNE provides a number of functions to extend Arcade. These can be used in the various Profiles available in the application.
Functions
AddField
AddField(FeatureSet, fielddefinition, fieldcalculator) -> FeatureSet
Adds a Field from a FeatureSet
Parameters
- FeatureSet: FeatureSet – The layer to filter.
- fielddefinition: Text | Dictionary – The field to add to the FeatureSet. If a String is provided, the field type will be indeterminate. If a definition is provided, it should provide name, nullable, and type properties.
- fieldcalculator: Text | Function – The SQL92 Expression to be used to calculate the field, or a user defined function
Examples
Add a Field. returns a featureset with a new field added
var result = AddField(mylayer, "newfield", "FID*10")
Add a Field with a definition. returns a featureset with a new field added, with a specific field definition
var result = AddField(mylayer, { name: "newfield", alias: "Friendly Name", type: "String", nullable: true}, "FID*10")
Add a Field using a function. returns a featureset with a new field added, with a specific field definition
function calcarea(feat) { return Area(Geometry(feat)) }
var result = AddField(mylayer, "myarea", calcarea)
Aggregate
Aggregate(FeatureSet, groupbyfields, fieldstats) -> FeatureSet
Returns a new featureset where aggregates have been calculated. The aggregate fields are equivalenent to the group by expression. The stats fields, are the aggregates to calculate. No geometry will be returned
Parameters
- FeatureSet: FeatureSet – The layer to filter.
- groupbyfields: Array – An array of field names to group by.
- fieldstats: Array – An array of field statistics to calculate.
Examples
Aggregate on a Field, and Calculate the Count. returns a Table where for each type of firsh, you have the Count of fish in the FeatureSet.
var result = Aggregate(mylayer, ["TypeOfFish"], ["Count()", "NumberOfFish"])
Aggregate on a Field, and Calculate, the Count, Sum, Min and Max Fields. returns a featureset which has been filtered using a SQL92 expression.
var result = Aggregate(mylayer, ["TypeOfFish","SubSpecies"], ["Count()", "NumberOfFish", "Sum(Remaining)", "NumRemaining", "Min(Legs)", "MinLegs" , "NumRemaining", "Max(Arms)", "MaxArms" ])
Aggregate on a Field, and Calculate the Sum of an Expression. returns a Table where for each type of firsh, you have the Count of fish in the FeatureSet.
var result = Aggregate(mylayer, ["TypeOfFish"], ["Sum(Field1 + Field2)", "NumberOfFishInAllBreedingGrounds"])
ApplicationProperty
ApplicationProperty(propertyname) -> *
Looks up an Application Property
**Be aware that some properties returned by the function may only be accessible to an admin user.
Parameters
- propertyname: Text – The name of a property of the application. One of the following values (commits-waiting, distance-units, area-units, webmap, token, organisation, user, theme, webmap-state, systeminfo, location-display-settings, location-capture-settings, app-state, active-template, item-info, theme-list, current-theme, is-in-edit-session)
Examples
Lookup number of commits waiting to save. Find out how many operations are waiting to be written to the database.
applicationproperty("commits-waiting")
Find out the distance units as a string.
applicationproperty("distance-units")
Find out the area units as a string.
applicationproperty("area-units")
Find out the webmap ID as a string.
applicationproperty("webmap")
Find out the access token for the app.
applicationproperty("token")
Returns the resource info from the portal.
applicationproperty("organisation")
Find the user info from the portal.
applicationproperty("user")
Find the current theme and its meta data for the application.
applicationproperty("theme")
Returns the state of the webmap.
applicationproperty("webmap-state")
Find out the AppRuntime info: software version, platform and whether the app is native or offline.
applicationproperty("systeminfo")
Current GPS display object with: currentGpsDisplay.showLocationOnMap: Shows the current GPS location on the map, currentGpsDisplay.showLocationAccuracy: Displays the Gps accuracy on the map as text, currentGpsDisplay.locationAutoPan: Flag to indicate if the map should be auto panned to keep the location on the map.
applicationproperty("location-display-settings")
Current GPS capture settings as an object: currentGpsCaptureSettings.accuracy: Required accuracy in meters, currentGpsCaptureSettings.captureMode: Use capture averaging, currentGpsCaptureSettings.averagingPointCount: Number of points to capture averaging with.
applicationproperty("location-capture-settings")
Find the state of the application. An object that includes current values for: dimensionMeasures, dpad, measure, rotation.
applicationproperty("app-state")
Find the active edit template.
applicationproperty("active-template")
Returns the application’s title, description, URL, ID and displayTitle.
applicationproperty("item-info")
Will return the current list of available themes.
applicationproperty("theme-list")
Will return the current theme e.g.: {id: 'blue',name: 'Glacier'}.
applicationproperty("current-theme")
Returns a boolean value to show if the user is in edit session or not.
applicationproperty("is-in-edit-session")
AssetTypeMetadata
AssetTypeMetadata(feat) -> Dictionary
Retrieve the asset type information for a network feature.
Parameters
- feat: Feature – The feature to get asset information for
Examples
Get the name of the asset type of a feature.. Access the assettypename property of the returned metadata.
var assetTypeName = AssetTypeMetadata($feature).assettypename
AssociatedFeatures
AssociatedFeatures(feat) -> Dictionary
Retrieves all association records and the related features for a specific network feature.
Parameters
- feat: Feature – The input feature to find all associations for
Examples
Retrieve the associations for a specific network feature.. Returns a dictionary of association information.
var associations = AssociatedFeatures($feature)
CenterOn
CenterOn(geom, pt) -> Geometry
Takes a Geometry and centers it on another point
Parameters
- geom: Geometry – The geometry to shift to another point
- pt: Point – The point the geometry should be centered on
Examples
Find a point along a line. Finds the point along a line
var newgeom = CenterOn(geom, pt)
Centroid
Centroid(geometry, keepnulls?) -> Point/FeatureSet
Returns the centroid of the input geometry. If a featureset is passed in, a new featureset will be created with the centroid of each of the features.
Parameters
- geometry: Geometry/FeatureSet – The geometry for which to calculate the centroid.
- keepnulls (Optional): Boolean – Flag to indicate if null geometries should be included in the result FeatureSet.
Examples
Returns the centroid of the given polygon.
Centroid(Geometry($feature))
Returns a FeatureSet with the centroid of each feature.
Centroid(layer)
ChangeShape
ChangeShape(FeatureSet, changefunction, keepnulls?, expectedtype?) -> FeatureSet
Changes the shape of every feature in a featureset, using a function
Parameters
- FeatureSet: FeatureSet – The layer to filter.
- changefunction: Function – The user defined function to be called for each feature in the featureset.
- keepnulls (Optional): Boolean – Flag to indicate if null geometries should be included in the result FeatureSet.
- expectedtype (Optional): Text – The type of geometry that is expected to be returned. point, polyline, polygon, multipoint, extent
Examples
Rotate all features by 90 degrees.. returns a featureset where all the features have been rotated
function rotateMe(feat) {
return rotate(geometry(feat),90)
}
var result = ChangeShape(mylayer, rotateMe)
Change a shape, but remove results that are null. returns a featureset where all the features have had centroid calculation. Lets the featureset know that it will always be a point.
function centroidMe(feat) {
return centroid(geometry(feat))
}
var result = ChangeShape(mylayer, centroidMe, false, "point")
ChangeShapeAndAttributes
ChangeShapeAndAttributes(FeatureSet, changefunction, keepnulls?, expectedtype?) -> FeatureSet
Changes the shape and attributes of every feature in a featureset, using a function
Parameters
- FeatureSet: FeatureSet – The layer to filter.
- changefunction: Function – The user defined function to be called for each feature in the featureset. This should return a new Feature, from which the attributes and geometry will be copied across. If null is returned the original feature will be kept. Only the attributes listed in the new Feature will be replaced, the other attributes of the original feature will be preserved.
- keepnulls (Optional): Boolean – Flag to indicate if null geometries should be included in the result FeatureSet.
- expectedtype (Optional): Text – The type of geometry that is expected to be returned. point, polyline, polygon, multipoint, extent
Examples
Rotate all features by 90 degrees.. returns a featureset where all the features have been rotated
function rotateMeAndChangeField(feat) {
return Feature(rotate(geometry(feat),90), "rotatefield", 10)
}
var result = ChangeShapeAndAttributes(mylayer, rotateMeAndChangeField)
CheckConnectivity
CheckConnectivity(checkextent) -> Dictionary
Checks the connectivity in a region (based on the configured Sweet connectivity model)
Parameters
- checkextent: Extent – The extent to check
Examples
Find all the Connectivity issues in a region.. Finds all the issues in a region
CheckConnectivity($mapextent)
Clone
Clone(value, deep?) -> Any
Clones an arcade variable. Deep clones will also clone all the child values in dictionary and arrays. Some types cannot be cloned (for example FeatureSets and FeatureSetCollections). A cloned Feature, Dictionary will not be immutable once cloned.
Parameters
- value: Any – The value to be cloned
- deep (Optional): Boolean – Flag to indicate if a deep clone is required. If deep all child objects will be cloned in an array or dictionary. A shallow clone will only clone the top level object.
Examples
Clone a Trace configuration
var newconfig = clone($traceconfig)
ClosestFacility
ClosestFacility(parameters, returnerror) -> Dictionary
Run the closest facility sync task against a Network service. Will return a Dictionary containing the result.
Parameters
- parameters: Dictionary – The parameters for the closest facility call. Based on the ESRI JS API Route Task
- returnerror: Boolean – Determines if the arcade script will error, or return a dictionary if the task fails.
Examples
Call closest facility service. returns the result from calling the closest facility service
var dd = closestfacility(myParameters, true)
return dd;
Connections
Connections(feature) -> Dictionary
Finds all the Connections for a Feature, based on the Sweet connectivity model.
Parameters
- feature: Feature – The feature to find all connections for.
Examples
Get the connections of a Feature. Finds the connections for a feature
Connections($feature)
ConnectWebSocket
ConnectWebSocket(webSocketKey, url, messageActionName, socketOptions?) -> true|Text
Opens a connection to a WebSocket. Return value will be true if successful or an error message if not.
Parameters
- webSocketKey: Text – A unique ID or key to identify the WebSocket connection in other scripts
- url: Text – The URL of the web socket to connect to
- messageActionName: Text – The name of the application Action to call when a message is received on the WebSocket or the socket status changes.
- socketOptions (Optional): Dictionary – Extended options (currently unused)
Examples
Connect to a WebSocket and send a message. Note that the Action to process messages must be defined elsewhere in the application.
ConnectWebSocket("exampleSocket", "wss://websocket.example.org", "HandleIncomingMessage");
if (GetWebSocketStatus("exampleSocket") == "connected") {
SendWebSocketMessage("exampleSocket", "Ping");
}
CreateAssociationRecord
CreateAssociationRecord(from, to, ruleType, contentVisibleOrPercentAlong?) -> Feature
Creates an association record feature, that conforms to the fields of utility network associations table
Parameters
- from: Dictionary – The dictionary should contain ‘layerid’ or ‘layername’, ‘feature’ and optionally ‘terminalid’ or ‘terminalname’.
- to: Dictionary – The dictionary should contain ‘layerid’ or ‘layername’, ‘feature’ and optionally ‘terminalid’ or ‘terminalname’.
- ruleType: Number | Text – Allowed values are 1 | 2 | 3 | 4 | 5 | 6 | ‘junction-junction-connectivity’ | ‘junction-junction’ | ‘containment’ | ‘attachment’ | ‘junction-edge-from-connectivity’ | ‘junction-edge-from’ | ‘junction-edge-midspan-connectivity’ | ‘junction-edge-midspan’ | ‘junction-edge-to-connectivity’ | ‘junction-edge-to’
- contentVisibleOrPercentAlong (Optional): Number | Boolean – If ruletype is containment, then can provide a boolean for IsContentVisible. If ruleType is Junction Edge Midspan Connectivity(5), then this parameter can containtain the percentAlong value.
Examples
Create an attachment. Builds an attachment between two features
var f= createAssociationRecord({layername:'Structure Junction', feature: fromfeat}, {layername:'Communications Junction', feature: tofeat}, 'attachment')
Create a containment. Builds a containment association between two features
var f= createAssociationRecord({layername:'Structure Junction', feature: fromfeat}, {layername:'Communications Junction', feature: tofeat}, 'containment', true)
Create a Junction Junction connectivity. Builds a junction junction association between two features
var f= createAssociationRecord({layername:'Communications Junction', feature: fromfeat, terminalid: 2}, {layername:'Communications Junction', feature: tofeat, terminalid: 3}, 'junction-junction')
Create a Junction Edge Midspan connectivity. Builds a junction edge midspan association between two features
var f= createAssociationRecord({layername:'Communications Edge Object', feature: fromfeat, terminalid: 2}, {layername:'Communications Edge Object', feature: tofeat, terminalid: 3}, 'junction-edge-midspan', 0.5)
CreateFeature
CreateFeature(properties) -> Feature
Creates a Feature which conforms to the set of fields in a Featureset. Optionally a feature template can be used to provide the default the values
Parameters
- properties: Dictionary – The dictionary should contain ‘layerid’ or ‘layername’, ‘geometry’ and optionally a ‘templatename’.
Examples
Get a new feature with all the correct fields for a layer. Builds a new feature with geometry and fields.
var f= createFeature({layername:'Trees', geometry: pt})
Get a new feature with all the correct fields for a layer, using a template. Builds a new feature with geometry and fields.
var f= createFeature({layername:'Trees', geometry: pt, templatename: 'Birch'})
Crossings
Crossings(geomA, geomB) -> Array<Point>
Finds all the crossings between two geometries
Parameters
- geomA: Geometry – The geometry to check for crossings
- geomB: Geometry – The second geometry to check for crossings
Examples
Find all the place two lines cross. Returns an array of points
var cros = crossings(lineA, lineB)
Csv
Csv(FeatureSet, num?) -> FeatureSet
Converts a featureset to a CSV String
Parameters
- FeatureSet: FeatureSet – The layer to be converted to a csv file
- num (Optional): Number – The max number of records to serialize. -1 will mean all records are put into the CSV file.
Examples
Convert layer to CSV. Converts the layer to a csv file
var result = csv(mylayer)
Convert the top 10 records in a csv layer. Create a csv file of the top 10 records
var result = Csv( orderBy(mylayer, "FIELDA ASC"),10);
CsvToLayer
CsvToLayer(sourcedata, columns, geometrydefinition?) -> FeatureSet
Parses a CSV String, into a FeatureSet
Parameters
- sourcedata: Text – A string containing the Source CSV Data
- columns: Dictionary – A list of columns to convert to fields in the Layer. The fields in the dictionary should be ‘name’, ‘type’ – optional String,Date,Integer,Number,Float,Long,Short. ‘dateformat’ – optional way of parsing a Date Field, and sourcename- optional (a different field name to lookup in the CSV).
- geometrydefinition (Optional): Dictionary – Details of how to extract the geometry from Fields in the CSV. Should be a Dictionary with xField, yField and spatialReference.
Examples
Read a CSV File into a Layer. returns a featureset with the contents of the CSV File
csvtolayer(sourcedata, [{"name": "field1", "type":"String"}, {"name": "field2", "type":"Date", "sourcename":"FieldNameInCsv", "format":"DD/MM/YYYY HH:mm"} ],{"xfield":"x", "yfield":"y", "spatialReference":{"wkid":102100})
Difference
Difference(inputGeometry, subtractor, keepnulls?) -> Geometry|FeatureSet
Performs the topological difference operation for the two geometries, or for each feature in a FeatureSet. The resultant geometry comes from `inputGeometry`, not the `subtractor`. The dimension of `subtractor` has to be equal to or greater than that of `inputGeometry`.
Parameters
- inputGeometry: Geometry | FeatureSet – The input geometry from which to subtract, or a featureset where each feature will be individually used in the subtraction.
- subtractor: Geometry | FeatureSet – The geometry to subtract from `inputGeometry`, or a featureset where each feature will be individually used in the subtraction.
- keepnulls (Optional): Boolean – Flag to indicate if null geometries should be included in the result FeatureSet..
Examples
Subtracts the given polygon area from the feature.. undefined
var subtractor = Polygon({ ... });
Difference(Geometry($feature), subtractor);
Subtracts the given polygon from every feature in a FeatureSet. undefined
var subtractor = Polygon({ ... });
Difference(layer, subtractor);
Creates a featureset where the features geometry is the geometry minus the features geometry.. undefined
var geom = Polygon({ ... });
Difference(geom, layer);
DisconnectWebSocket
DisconnectWebSocket(webSocketKey) -> true|Text
Closes a connection to a WebSocket. Return value will be true if successful or an error message if not.
Parameters
- webSocketKey: Text – A unique ID or key to identify the WebSocket connection in other scripts
Examples
Disconnect from a WebSocket.
DisconnectWebSocket("exampleSocket");
Dissolve
Dissolve(FeatureSet, groupbyfields, fieldstats) -> FeatureSet
Returns a new featureset where aggregates have been calculated. The geometries will be unioned together. The aggregate fields are equivalenent to the group by expression. The stats fields, are the aggregates to calculate.
Parameters
- FeatureSet: FeatureSet – The layer to filter.
- groupbyfields: Array<Text> – An array of field names to group by.
- fieldstats: Array – An array of field statistics to calculate.
Examples
Dissolve on a Field, and Calculate the Count. returns a Table where for each type of firsh, you have the Count of fish in the FeatureSet.
var result = Dissolve(mylayer, ["TypeOfFish"], ["Count()", "NumberOfFish"])
Dissolve on a Field, and Calculate, the Count, Sum, Min and Max Fields. returns a featureset which has been filtered using a SQL92 expression.
var result = Dissolve(mylayer, ["TypeOfFish","SubSpecies"], ["Count()", "NumberOfFish", "Sum(Remaining)", "NumRemaining", "Min(Legs)", "MinLegs" , "NumRemaining", "Max(Arms)", "MaxArms" ])
Dissolve on a Field, and Calculate the Sum of an Expression. returns a Table where for each type of firsh, you have the Count of fish in the FeatureSet.
var result = Dissolve(mylayer, ["TypeOfFish"], ["Sum(Field1 + Field2)", "NumberOfFishInAllBreedingGrounds"])
EncodeHtmlAttribute
EncodeHtmlAttribute(value) -> Text
Encodes a string into a form that can be used as an HTML attribute
Parameters
- value: Text – The value to be encoded
Examples
Convert a String into an HTML attribute. Safely sanitises characters to safely add a string to html
EncodeHtmlAttribute("thevalue")
ExtentCachedFeatures
ExtentCachedFeatures(layer) -> FeatureSet
Speeds up script execution by caching the features in the current map extent for this FeatureSet. As the extent changes, this FeatureSet will be re-evaluated and the current set cached. Note that the maximum number of records that are returned from the cached FeatureSet is controlled by the maximum record count setting of the FeatureLayer (maxRecordCount).
Parameters
- layer: FeatureSet – The layer to cache in memory for the current viewing extent.
**Be aware that the layer variable should be set to an un-filtered map layer as otherwise performance will significantly reduce.
Examples
Optimise use of layer on the map. Keeps the current map extent features in memory ready to be used for this layer.
ExtentCachedFeatures(FeatureSetByName($map, 'Sites of Interest')
FeatureBuilder
FeatureBuilder(properties) -> Array<Feature>
Builds a set of features given a number of properties
Parameters
- properties: Dictionary – The dictionary should contain ‘layerid’ or ‘layername’, a geometry from which to bulk create features from, a ‘method’ describing the the approach taken to feature creation, and optionally a ‘templatename’. The following methods are supported: ‘multiple-point-features’ | ‘point-at-start-of-line’ | ‘point-at-end-of-line’ | ‘point-at-every-vertex-of-line’ | ‘point-at-every-vertex-of-line-except-end’ | ‘point-at-every-vertex-of-line-except-start’ | ‘point-at-every-vertex-of-line-except-start-and-end’ | ‘multiple-single-part-lines’ | ‘centroid’ | ‘multiple-polygon-features’ | ‘single-line-feature-boundary’ | ‘point-at-start-of-polygon’ | ‘point-at-every-vertex-of-polygon’ | ‘point-at-every-vertex-of-polygon-except-start’ | ‘buffer’
Examples
Get a new point feature using ‘multiple-point-features’. This operation expects a point geometry to be used. It will create a new feature initialised with the same geometry
var feats = featureBuilder({method: 'multiple-point-features', geometry: pt, layername: 'Trees', templatename: 'Birch')
Get a new point feature at the start of a line ‘point-at-start-of-line’. This operation get a feature at the start of a line. It can optionally take an offset-distance and side (left or right), and/or a distance-along. The distance-along should specify the type of distance, ‘proportional’ or ‘distance’
var feats = featureBuilder({method: 'point-at-start-of-line', geometry: myLine, layername: 'Trees', templatename: 'Birch', 'offset-distance': 10, 'offset-side': 'left', 'distance-along': 10, 'distance-along-type':'distance')
Get a new point feature at the end of a line ‘point-at-end-of-line’. This operation get a feature at the end of a line. It can optionally take an offset-distance and side (left or right), and/or a distance-along. The distance-along should specify the type of distance, ‘proportional’ or ‘distance’
var feats = featureBuilder({method: 'point-at-end-of-line', geometry: myLine, layername: 'Trees', templatename: 'Birch', 'offset-distance': 10, 'offset-side': 'left', 'distance-along': 10, 'distance-along-type':'distance')
Get new point features at every vertex of a line ‘point-at-every-vertex-of-line’. This operation gets features for every vertex of a line. It can optionally take an offset-distance and side (left or right), and/or a distance-along. The distance-along should specify the type of distance, ‘proportional’ or ‘distance’
var feats = featureBuilder({method: 'point-at-every-vertex-of-line', geometry: myLine, layername: 'Trees', templatename: 'Birch', 'offset-distance': 10, 'offset-side': 'left', 'distance-along': 10, 'distance-along-type':'distance')
Get new point features at every vertex of a line, except the end ‘point-at-every-vertex-of-line-except-end’. This operation gets features for every vertex of a line. It can optionally take an offset-distance and side (left or right), and/or a distance-along. The distance-along should specify the type of distance, ‘proportional’ or ‘distance’
var feats = featureBuilder({method: 'point-at-every-vertex-of-line-except-end', geometry: myLine, layername: 'Trees', templatename: 'Birch', 'offset-distance': 10, 'offset-side': 'left', 'distance-along': 10, 'distance-along-type':'distance')
Get new point features at every vertex of a line, except the start ‘point-at-every-vertex-of-line-except-start’. This operation gets features for every vertex of a line. It can optionally take an offset-distance and side (left or right), and/or a distance-along. The distance-along should specify the type of distance, ‘proportional’ or ‘distance’
var feats = featureBuilder({method: 'point-at-every-vertex-of-line-except-start', geometry: myLine, layername: 'Trees', templatename: 'Birch', 'offset-distance': 10, 'offset-side': 'left', 'distance-along': 10, 'distance-along-type':'distance')
Get new point features at every vertex of a line, except the start and end ‘point-at-every-vertex-of-line-except-start-and-end’. This operation gets features for every vertex of a line. It can optionally take an offset-distance and side (left or right), and/or a distance-along. The distance-along should specify the type of distance, ‘proportional’ or ‘distance’
var feats = featureBuilder({method: 'point-at-every-vertex-of-line-except-start-and-end', geometry: myLine, layername: 'Trees', templatename: 'Birch', 'offset-distance': 10, 'offset-side': 'left', 'distance-along': 10, 'distance-along-type':'distance')
Get new point feature at the centroid of a geometry. This operation gets a new feature at the centroid of a Polygon
var feats = featureBuilder({method: 'centroid', geometry: myPoly, layername: 'Trees', templatename: 'Birch')
Get a new polygon feature using ‘multiple-polygon-features’. This operation expects a polygon geometry to be used. It will create a new feature initialised with the same geometry
var feats = featureBuilder({method: 'multiple-polygon-features', geometry: pt, layername: 'Boundaries', templatename: 'Site Boundary')
Get a new polyline feature using the boundary of a polyline, using ‘single-line-feature-boundary’. This operation expects a polygon geometry to be used. It will create a new feature initialised with a line representing the boundary
var feats = featureBuilder({method: 'single-line-feature-boundary', geometry: pt, layername: 'Boundaries', templatename: 'Site')
Get a new point from the first vertex of a polygon using ‘point-at-start-of-polygon’. This operation gets a features for the first vertex of a polygon
var feats = featureBuilder({method: 'point-at-start-of-polygon', geometry: myLine, layername: 'Trees', templatename: 'Birch')
Get new point features at every vertex of a polygon using ‘point-at-every-vertex-of-polygon’. This operation gets features for every vertex of a polygon
var feats = featureBuilder({method: 'point-at-every-vertex-of-polygon', geometry: myLine, layername: 'Trees', templatename: 'Birch')
Get new point features at every vertex of a polygon except the first point using ‘point-at-every-vertex-of-polygon-except-start’. This operation gets features for every vertex of a polygon except the first point
var feats = featureBuilder({method: 'point-at-every-vertex-of-polygon-except-start', geometry: myLine, layername: 'Trees', templatename: 'Birch')
Get new feature by buffering an existing geometry ‘buffer’. This operation gets a new feature as a buffer of an existing one
var feats = featureBuilder({method: 'buffer', geometry: myLine, layername: 'Trees', templatename: 'Birch', distance: 10)
FeatureCollection
FeatureCollection(definition) -> FeatureSet
DEPRECATED: Connects to a Feature Service Layer, and returns the features as a Featureset.
Parameters
- definition: Text | Dictionary – The feature collection JSON. If a String is used it will be parsed to find the FeatureCollection elements.
Examples
FeatureCollection from a String. returns a featureset which iterates over the features in the FeatureCollection.
var featureset = FeatureCollection("")
FeatureCollection from a Dictionary. returns a featureset which iterates over the features in the FeatureCollection.
var featureset = FeatureCollection({})
FeatureLayer
FeatureLayer(url, credentials?, fieldlist?) -> FeatureSet
DEPRECATED: Connects to a Feature Service Layer, and returns the features as a Featureset.
Parameters
- url: Text – The URL of the layer, including the layer ID.
- credentials (Optional): Dictionary – The credentials to use to connect to the service. This should be based on a token.
- fieldlist (Optional): Array – List of fields to fetch from the layer.
Examples
Connect to a public feature layer. returns a featureset which iterates over all of the features.
var featureset = FeatureLayer("//services.arcgis.com/.../FeatureServer/0")
Connect to a feature layer with credentials. returns a featureset which iterates over all of the features.
var featureset = FeatureLayer("//services.arcgis.com/.../FeatureServer/0")
Connect to a feature layer limiting the fields returned. returns a featureset, with only the listed fields included.
var featureset = FeatureLayer("//services.arcgis.com/.../FeatureServer/0", null, ["FieldA","FieldB"])
GdbVersion
GdbVersion(layer) -> Text
Finds the current gdb version for a layer
Parameters
- layer: Featureset – The Featureset for which to get the version
Examples
Find the gdb version. Finds the gdb version of a layer
var version = gdbVersion(layer)
GdbVersionCreate
GdbVersionCreate(url_or_layer, name, description?, accessPermission?) -> Dictionary
Creates a new gdb Version.
Parameters
- url_or_layer: Text | FeatureSet – The url of the VersionManagementServer, or a Featureset to derive this
- name: Text – The name of the version to be created
- description (Optional): Text – A drscription for the version
- accessPermission (Optional): Text – The access permission. Deafault ‘private’. Can be ‘private’ | ‘public’ | ‘protected’ | ‘hidden’.
Examples
Create a gdb version. Makes a new version
var newversion = gdbVersionCreate(layer, 'newversionname')
gdbVersionList
gdbVersionList(url_or_layer, ownerFilter?, includeHidden?) -> Dictionary
Lists all the gdb versions that have been created
Parameters
- url_or_layer: Text | FeatureSet – The URL of the VersionManagementServer, or a Featureset to derive this
- ownerFilter (Optional): Text – User id to use as a filter
- includeHidden (Optional): Boolean – Default false
Examples
List versions. List all versions
var newversion = gdbVersionList(layer)
Geocode
Geocode(search, field_or_options?, options?) -> FeatureSet|Dictionary
Fetches the location for a String. If used with a featureset and a Field, will geocode every address in a table.
Parameters
- search: Text | FeatureSet | Dictionary – The text to search (single line), or the featureset to Geocode. If a Dictionary is provided, these will be considered as Address Fields for the query.
- field_or_options (Optional): Text | Dictionary – If the first parameter is a FeatureSet, then this parameter holds the Field Name or SQL Expression which is to be used for the address query. If the first parameter is a String or Dictionary, this will hold the locator options. See locator options below.
- options (Optional): Dictionary – If the first parameter is a FeatureSet, then this parameter holds locator options. This field can have ‘categoroes’, ‘countrycode’, ‘distance’, ‘outFields, locator: {url:…}, keepnulls
Examples
Geocode an Address. Perform a simple geocode
geocode('HP20 2QZ')
Geocode all Features in a FeatureSet. Geocode all the features in a featureset, throwing away any records that do not match
geocode(myfeatureset, 'FIELD1', { keepnulls: false})
GetWebSocketStatus
GetWebSocketStatus(webSocketKey) -> connected|disconnected|connecting|errored
If a connection to a WebSocket is available in the running application, fetches the current status of that socket. Will return null if the socket is not registered.
Parameters
- webSocketKey: Text – A unique ID or key to identify the WebSocket connection
Gp
Gp(url, gpparameters, identity?, timing?, returnerror?) -> Dictionary
Run a Geoprocessing Task. Will return a Dictionary containing the result.
Parameters
- url: Text – The url of the GP task
- gpparameters: Dictionary – The parameters of the GP task
- identity (Optional): Identity – The identity to use when calling the GP task.
- timing (Optional): Number – The number of seconds to allow the GP task to run for, before erroring. Default is 5 minutes
- returnerror (Optional): Boolean – Flag to indicate if an error object should be returned if the GP task fails. Default is false. If an error occurs, the returned dictionary will have a field called ‘error’ with the message.
Examples
Call a GP task. returns a Viewshed result.
var dd =gp("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed",
{
Input_Observation_Point: [Point({x:-6061190.600342937,y:3796137.309652354,spatialReference: {wkid: 102100}})],
Viewshed_Distance: { distance: 2000, units: "esriMeters" }
}, null);
return dd;
Grid
Grid(bbox, size, origin?) -> FeatureSet
Generates a Layer with Grid Squares, that have been generated within a bounding box.
Parameters
- bbox: Polygon | Extent – An extent representing the bounding box of the grid. If a polygon is used, the squares are clipped to the polygon, but the bounding box of the polygon is used.
- size: Number – The width and height of the grid square in meters
- origin (Optional): Point – An alternative origin for the grid squares to start at. Only grid squares that intersect the bounding box will be returned.
Examples
Generate a set of Grid Squares. returns a featureset with grid squares in
progress({"%grid%:buildinggrid": "Building Grid {{read}}"});
var grid = grid(bbox, 5000);
HasWebSocket
HasWebSocket(webSocketKey) -> Boolean
Checks if a connection to a WebSocket is available in the running application.
Parameters
- webSocketKey: Text – A unique ID or key to identify the WebSocket connection
Intersection
Intersection(geometry1, geometry2, keepnulls?) -> Geometry|FeatureSet
Constructs the set-theoretic intersection between two or more geometries and returns a new geometry, or if using a FeatureSet, will find the intersection for every feature in the featureset.
Parameters
- geometry1: Geometry | FeatureSet – The geometry or featureset to intersect with `geometry2`.
- geometry2: Geometry – The geometry to intersect with `geometry1`.
- keepnulls (Optional): Boolean – Flag to indicate if null shapes should be kept. Defaults to true, meaning null geometries will be returned if there is no intersection.
Examples
Returns the area common to both polygons. undefined
var geom2 = Polygon({ ... });
Area(Intersection(Geometry($feature), geom2), 'square-miles');
Find the intersection for every feature in a featureset with a geometry, but only return if it is not null.. undefined
var geom2 = Polygon({ ... });
intersection(layer, geom2, false);
Kmeans
Kmeans(data, num, clusteridentifier) -> Dictionary
Partition a dataset into a number of clusters based on their proximity using kMeans clustering.
Parameters
- data: FeatureSet – The set of data points to cluster.
- num: Number – The number of clusters to generate
- clusteridentifier: Text – A Field name to be added to the data, to represent which cluster a feature belongs to.
Examples
Generate a set of Grid Squares. returns a featureset with grid squares in
progress({"%kmeans%:readingdata": "Reading Customers {{read}}", "%kmeans%:solving": "Finding Clusters","%kmeans%:writing" : "Checking Clusters" });
var clusters = kmeans(data, 5, "ClusterId");
var centroids = clusters.centroids; // Array of Points
var datawithclusterid = clusters.cursor; // Original data with ClusterId appended as a Field
LookupUser
LookupUser(userid) -> Dictionary
Looks up a user in your Portal, based on their User ID
Parameters
- userid: Text – The userid that you wish to lookup.
Examples
Lookup a User in your Portal. returns a user information for the given user
lookupuser("rsmith")
MapLayer
MapLayer(map, title, id?) -> FeatureSet
DEPRECATED: Finds a layer in a Map and returns it as a FeatureSet
Parameters
- map: Map – A Map which contains a collection of layers. Each layer has an ID and Title
- title: Text – The title of the layer. The map layers will be searched and the appropriate layer returned.
- id (Optional): Text – The id of the layer. If title is not provided, the map layers will be searched for a layer with this id.
Examples
MapLayer by Title. Get a MapLayer using its title
var featureset = MapLayer($map, "Cycle Hire")
MapLayer by ID. Get a MapLayer usings its ID in the Map
var featureset = MapLayer($map, "", "DemoLayerWM_1117")
PixelDistanceToMapUnit
PixelDistanceToMapUnit(distance?) -> Number
Gets a distance in pixel units and converts it to the map units
Parameters
- distance (Optional): Number – The number of pixels. Defaults to 1
Examples
Get a distance in map units. Calculate 10 pixels in map units
var currentV = pixelDistanceToMapUnit(10)
PointAlongLine
PointAlongLine(line, distance) -> Point
Finds a point, a given distance along a line
Parameters
Examples
Find a point along a line. Finds the point along a line
var pt = PointAlongLine(line, 10)
Progress
Progress(message) -> Null
Report Progress to the user. This function allows messages to be displayed in the calling Application, wilst the Arcade Script is running. This is useful for long running scripts where you wish to indicate in the Application what the script is doing.
Parameters
- message: Text | Dictionary – The string to send back to the user
Examples
Report Progress. Send a message to the calling application.
progress("Fetching Data")
Report Progress from within a long running function. The regiongrow function can take some time, it will call progress regularly as it runs. The progress function is called before regiongrow to configure how it will report its progress.
progress({"%regiongrow%:readingseeds": "Reading Seeds {{read}}", "%regiongrow%:readinggeog" : "Reading Geographies {{read}}", "%regiongrow%:growing" : "Generating Regions", "%regiongrow%:union" : "Merging Cells", "%regiongrow%:writing" : "Writing Regions" });
var regions = regiongrow(seeds, geography);
Prompt
Prompt(title, message, oklabel?, cancellabel?, alternatelabel?) -> true | false | null
Show a prompt box with ok, cancel, alternate buttons (cancel and alternate are optional). Will return true if the ok button is clicked, false for the cancel or null for close
Parameters
- title: Text – The title for the prompt
- message: Text – The message for the prompt
- oklabel (Optional): Text – The label for the ok button. Will default to ‘Yes’
- cancellabel (Optional): Text – The label for the cancel button. Will default to ‘No’. If null or ” is provided, the button will not be shown.
- alternatelabel (Optional): Text – The label for the alternate button. Will default to null. If null or ” is provided, the button will not be shown.
Examples
Show a simple yes/no prompt. Show a simple yes/no
var sym = prompt('Some title', 'Do you wish to continue');
RegionGrow
RegionGrow(seeds, referencegeography) -> FeatureSet
Generates a Layer where polygons have been created around seedpoints, by merging neighbouring geometries from a reference set.
Parameters
- seeds: FeatureSet – The set of seed points from which to grow regions from.
- referencegeography: FeatureSet – The set of geographies to be used for creating regions. Neighbours will be merged around seed points.
Examples
Generate a set of Grid Squares. returns a featureset with grid squares in
progress({"%regiongrow%:readingseeds": "Reading Seeds {{read}}", "%regiongrow%:readinggeog" : "Reading Geographies {{read}}", "%regiongrow%:growing" : "Generating Regions", "%regiongrow%:union" : "Merging Cells", "%regiongrow%:writing" : "Writing Regions" });
var regions = regiongrow(seeds, geography);
ReleaseEditLocks
ReleaseEditLocks(clearSelectionFirst?) -> Boolean
When using multi-user locking, remove any areas in the map that have been locked for editing and inform any connected applications. Locks cannot be released if there are active selected features. Will return true if the locks were released, false otherwise.
Note: in normal operation there will be no need to use this function, multi-user locking and releasing will be handled automatically. This should only be used in specific circumstances, for example to release one geographical extent before moving to another or when integrating the editor window using <iframe> or similar.
Parameters
- clearSelectionFirst (Optional): Boolean – If true clears any selections in the map before releasing locks. False by default.
RemoveField
RemoveField(FeatureSet, fieldname) -> FeatureSet
Removes a Field from a FeatureSet
Parameters
- FeatureSet: FeatureSet – The layer to filter.
- fieldname: Text – The field to remove
Examples
Remove the ADDRESS Field. returns a featureset which has the address field removed
var result = RemoveField(mylayer, "ADDRESS")
ReverseGeocode
ReverseGeocode(search, field_or_options?, options?) -> FeatureSet|Dictionary
Reverse geocodes a point, or all the records in a Feature FeatureSet.
Parameters
- search: Point | FeatureSet – The point or set of features to reverse geocode.
- field_or_options (Optional): Text | Dictionary – If the first parameter is a FeatureSet, then this parameter holds the Field Name to be added to the FeatureSet. If the first parameter is a Point, this holds the locator options (see below)
- options (Optional): Dictionary – If the first parameter is a FeatureSet, then this parameter holds locator options. This field can have ‘categoroes’, ‘countrycode’, ‘distance’, locator: {url:…}
Examples
Reverse Geocode a Point. Perform a simple reverse geocode
reverseGeocode(Point({x:-6061190.600342937,y:3796137.309652354,spatialReference: {wkid: 102100}}))
Reverse geocode all Features in a FeatureSet. Finds the address for all the features in the FeatureSet
reverseGeocode(myfeatureset, 'ADDRESS')
Route
Route(parameters, returnerror) -> Dictionary
Run the route sync task against a Network service. Will return a Dictionary containing the result.
Parameters
- parameters: Dictionary – The parameters for the route call. Based on the ESRI JS API Route Task
- returnerror: Boolean – Determines if the arcade script will error, or return a dictionary if the service area task fails.
Examples
Call network service route. returns the result from calling the route service
var dd =route(myParameters, true)
return dd;
SendWebSocketMessage
SendWebSocketMessage(webSocketKey, message) -> Boolean|Text
Sends a message to an open WebSocket connection. Return value will be true if successful or an error message if not.
Parameters
- webSocketKey: Text – A unique ID or key to identify the WebSocket connection in other scripts
- message: Any – The message to send to the web socket (typically a String but could be binary data)
Examples
Connect to a WebSocket and send a message. Note that the Action to process messages must be defined elsewhere in the application.
ConnectWebSocket("exampleSocket", "wss://websocket.example.org", "HandleIncomingMessage");
SendWebSocketMessage("exampleSocket", "Ping");
ServiceArea
ServiceArea(parameters, returnerror) -> Dictionary
Run the solveServiceArea geoprocessing task against a Network. Will return a Dictionary containing the result.
Parameters
- parameters: Dictionary – The parameters for the serviceArea call. Based on the ESRI JS API Service Area Task
- returnerror: Boolean – Determines if the arcade script will error, or return a dictionary if the service area task fails.
Examples
Call solveArea. returns the result from calling serviceArea
var dd = serviceArea(myParameters, true)
return dd;
State
State(key, value?, semantics?) -> Any
Stores and sets state that can be used across scripts
Parameters
- key: Text – The key of the state. This will be used to save or fetch the state
- value (Optional): Any – The value to be stored in State. This must be a simple type, such as String, Number, Date, Geometry, Dictionary, Array. It cannot contain a FeatureSet
- semantics (Optional): Dictionary – This is a dictionary which can provide meta data about how long a value should be stored in state. For example {‘type’:’operation’}, will only keep the state for the duration of the executing operation. {‘type’:’time’, ‘timeout’, 1000}, will only keep the state for 1000 milliseconds
Examples
Get a value from state. Gets a value from State
var currentV = state('keyA')
Set a value in state. Stores a value in the state
state('keyA', 'somevalue')
SymbolFromFeature
SymbolFromFeature(feat, layer, format?) -> Dictionary|Text
Provided with a layer and feature, the function will return an ArcGIS Rest based symbol
Parameters
- feat: Feature – The feature to get the symbol for
- layer: Dictionary – A dictionary which references a layer, by providing a layername or layerid
- format (Optional): Text – The format to return the symbol in. Values can be ‘text’ or ‘dictionary’. Defaults to ‘text’
Examples
Get the symbol for a feature in a layer. Get the symbol definition
var sym = symbolFromFeature(feat, { layername:'Trees'})
SymmetricDifference
SymmetricDifference(leftGeometry, rightGeometry, keepnulls?) -> Geometry
Performs the Symmetric difference operation on the two geometries, or for each feature in a FeatureSet. The symmetric difference includes the parts of both geometries that are not common with each other.
Parameters
- leftGeometry: Geometry | FeatureSet – The geometry instance to compare to `rightGeometry` in the XOR operation, or a featureset where each feature will be individally be used in the XOR operation.
- rightGeometry: Geometry | FeatureSet – The geometry instance to compare to `leftGeometry` in the XOR operation, or a featureset where each feature will be individally be used in the XOR operation.
- keepnulls (Optional): Boolean – Flag to indicate if null geometries should be included in the result FeatureSet.
Examples
Returns a polygon representing areas where both inputs do not overlap. undefined
var geom2 = Polygon({ ... });
SymmetricDifference(Geometry($feature), geom2));
Returns a polygon representing areas where both inputs do not overlap. undefined
var geom2 = Polygon({ ... });
SymmetricDifference(Geometry($feature), geom2));
Returns a featureset where each feature has been XOR with the input geometry. undefined
var geom2 = Polygon({ ... });
SymmetricDifference(layer, geom2));
Returns a featureset where the input geometry has been Xor with the each feature in the FeatureSet, to create a new FeatureSet.. undefined
var geom2 = Polygon({ ... });
SymmetricDifference( geom2, layer));
ToScreenPoint
ToScreenPoint(pt) -> Dictionary
Converts a map point into screen coordinates
Parameters
- pt: Point – The point to be converted to screen coordinates
Examples
Find the screen point. Returns a dictionary with x and y in screen coordinates
var sp = toScreenPoint(pt); console(sp.x + ',' + sp.y)
UnfilteredFeatureSet
UnfilteredFeatureSet(FeatureSet, removewebmapfilter) -> FeatureSet
Unfilters a featureset by removing the layer filter set in the builder (and optionally the layer filter set in the webmap)
Parameters
- FeatureSet: FeatureSet – The layer to unfilter.
- removewebmapfilter: Boolean – If set to true, layer filters in the webmap and builder are both removed. If set to false, only the layer filter in builder is removed
Examples
Unfilter to just the service. Gets a featurelayer based on the raw service
var featureset = UnfilteredFeatureSet(fs, true)
Unfilter to just the webmap’s original filter. Get a featurelayer as originally setup in the webmap
var featureset = UnfilteredFeatureSet(fs,false)
Union
Union(geometries) -> Geometry
Constructs the set-theoretic union of the geometries in the input array or a featureset and returns a single Geometry. All inputs must have the same geometry type and share the same spatial reference.
Parameters
- geometries: Array<Geometry> | FeatureSet – An array of geometries to union into a single geometry, or a FeatureSet.
Examples
Returns a single polygon representing the union of both inputs. undefined
var geom2 = Polygon({ ... });
Union([ Geometry($feature), geom2 ]);
Returns a single polygon for all the features in a featureset. undefined
Union(myFeatureSet);
UtilityNetworkLayers
UtilityNetworkLayers() -> Array
This function returns an array containing the metadata for the utility network layers in the current map.
Examples
Retrieve a collection of utility network layers in the current map.. Returns an array of dictionaries containing metadata for layers. Each dictionary includes the following properties: ‘layertitle’, ‘layerid’, ‘networksourceid’, ‘isstructurenetwork’, and ‘featureclassusagetype’.
var mapUtilityLayers = UtilityNetworkLayers()
UtilityNetworkMetadata
UtilityNetworkMetadata() -> Dictionary
This function returns a dictionary that includes the metadata information about the utility network service currently being used in the application.
Examples
Get the metadata for the current utility network.. store the metadata in a variable
var metadataUN = UtilityNetworkMetadata()
UtilityNetworkSelectedFeatures
UtilityNetworkSelectedFeatures() -> Array<Text>
Creates a list of the global IDs for all selected utility network features in the current selection
Examples
Retrieve a collection of utility network features that have been selected.. Returns an array of the globalid field values for every selected feature in the utility network.
var selectedUNFeatures = UtilityNetworkSelectedFeatures()
Voronoi
Voronoi(seeds, bbox?) -> FeatureSet
Generates a Voronoi set of polygons, given a layer of seed points, and a bounding box.
Parameters
- seeds: FeatureSet – A layer containing points, which are to be used as the seeds for the Voronoi.
- bbox (Optional): Extent | Polygon – The bounding box for the polygons. If a polygon is used, the voronoi will use the bounding box of the polygon, but then the resulting polygons will be clipped to the original geometry.
Examples
Generate a set of Voronoi Polygonsr. returns a featureset with polygons for all the seed points.
progress({"%voronoi%:readingdata": "Reading Sales Team {{read}}","%voronoi%:calculating" : "Generating Territories","%voronoi%:writing" : "Writing Territories" })
var vv = voronoi(seeds, extent(allboundary));
Wait
Wait(delay-in-milliseonds) -> Boolean
Forces the script execution to wait for a period of milliseconds
Parameters
- delay-in-milliseonds: Number – Number of Milliseconds to wait
Examples
Wait for a second. Wait for a second.
wait(1000)
WaitForCommits
WaitForCommits() -> Boolean
Forces Sweet to pause execution until the commit queue is empty. Ensures the server has the same contents as the app. This function should be used at the beginning of a script to ensure all changes are on the server, before new filters are applied to layers, or the map is reset.
Examples
Wait until the commits stack is empty. Pause the app, until the commits are finished.
WaitForCommits()
Webhook
Webhook(url, query?, form?, sendFormat?, responseFormat?) -> Dictionary|Text
Calls an external URL, and returns the result
Parameters
- url: Text – The url of the Webhook
- query (Optional): Dictionary – The parameters to pass in the URL querystring. The default is null. If this value exceeds the length allowed for a URL, the request will be converted to a POST request (if no form parameter is provided)
- form (Optional): Dictionary | Text – The content to pass in the body of the request. If this parameter is provided, the request will be sent as a POST request. If a Dictionary it will be encoded as application/x-www-form-urlencoded, unless overriden by the ‘sendFormat’ parameter. If a string, it will be placed in the body with no encoding. The default is null.
- sendFormat (Optional): Text – ‘body’ or ‘form’. The default is ‘form’. This overrides how the ‘form’ parameter is encoded. If the value is ‘body’, the contents of the form parameter will be converted to a string and sent as the body. Otherwise the form parameter is expected to be a Dictionary that is sent as a POST request application/x-www-form-urlencoded.
- responseFormat (Optional): Text – text or json. The default is ‘json’
Examples
Get a next sequence value. Creates a row in an online table, gets its object ID and then deletes it.
var result = webhook('https://.../FeatureServer/0/addFeatures',
{ f: 'json' },
{ "features": [Feature(null, "name", "A")] })
var a = result.addResults[0].objectId
var result = webhook('https://.../FeatureServer/0/deleteFeatures',
{ f: 'json' }, { "objectIds": a });
return a
WorkflowManager
WorkflowManager(url, identity, actionname, actionparameters) -> *
Performs an operation in Workflow Manager
Parameters
- url: Text – The url of the Workflow Manager.
- identity: Identity – The identity to use when calling Workflow Manager
- actionname: Text – The name of the action to perform. One of the following values (create-job, create-hold, reopen-job, close-job, delete-job, list-job-activity, log-job-activity, unassign-job, update-job, assign-job, get-job, get-job-notes, update-job-notes, send-notification, extended-properties-add-record, extended-properties-delete-record, extended-properties-update-record, extended-properties, get-steps, get-step, step-canrun, step-log-comment, assign-steps, step-movenext, step-comments, get-current-step, steps-markasdone, steps-execute, user, steps-assign)
- actionparameters: Dictionary – The parameters of the action. See the Workflow Manager documentation for expected values.
Examples
Get the details of a Job. Queries Workflow Manager and gets a hob.
WorkflowManager('//..../WMServer', $userIdentity, 'get-job', {'jobid', '3833-38383'})