Hide Table of Contents
esri/dijit/util
esri/layer/pixelFilters
esri/process
esri/workers
Class: StreamLayer

require(["esri/layers/StreamLayer"], function(StreamLayer) { /* code goes here */ });

Description

(Added at v3.6)
The stream layer extends the feature layer to add the ability to connect to a stream of data using HTML5 WebSockets. It connects to a server that emits geographic features continuously. While the feature layer is used to map relatively static data, the stream layer is suitable when you would like to map dynamic streams of data that are unbounded and continuous. When a stream layer is added to a map, users are able to see any real-time updates pushed out by the server.

A real-time-enabled data server is required in order to use this class. The ArcGIS GeoEvent Processor for Server is a tool you may use to set up and configure your data stream. In addition, version 10.3 of ArcGIS GeoEvent Extension for Server exposes stream services. To learn more about this, please see the Stream Services documentation.

You may also use your own web socket server, as long as it emits geographic features in the Esri JSON format.

The number of features coming from a real-time feed can overload the browser and make the browser unresponsive. Use the purgeOptions construction option to define rules that specify how to remove data when new messages are received and the layer is refreshed.

NOTE: WebSockets are a feature of HTML5. Most browsers are supporting WebSockets in recent versions. However, they are not supported by all versions of all browsers. To get more information about WebSockets and to test if a browser supports WebSockets, visit WebSocket.org.

Samples

Search for samples that use this class.

Class hierarchy

esri/layers/Layer
|_esri/layers/GraphicsLayer
  |_esri/layers/FeatureLayer
    |_esri/layers/StreamLayer

Constructors

NameSummary
new StreamLayer(url, options?)Creates a new StreamLayer with a service URL.
new StreamLayer(featureCollectionObject, options?)Creates a new StreamLayer with a FeatureCollection object.

Properties

NameTypeSummary
advancedQueryCapabilitiesObjectAn object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents.
allowUpdateWithoutMValuesBooleanIndicates whether attribute features containing m-values can be edited.
capabilitiesStringInformation about the capabilities enabled for this layer.
classNameStringclass attribute of the layer's node.
copyrightStringCopyright information for the layer.
credentialCredentialProvides credential information for the layer such as userid and token if the layer represents a resource that is secured with token-based authentication.
dataAttributesString | String[]List of attribute fields added as custom data attributes to graphics node.
defaultDefinitionExpressionStringMetadata describing the default definition expression for the layer as defined by the service.
defaultVisibilityBooleanIndicates the default visibility for the layer.
descriptionStringThe description of the layer as defined in the map service.
displayFieldStringThe name of the layer's primary display field.
fieldsField[]The array of fields in the layer.
fullExtentExtentThe full extent of the layer.
geometryTypeStringGeometry type of the features in the layer.
graphicsGraphic[]Array of features in the layer.
htmlPopupTypeStringThe html popup type defined for the layer.
idStringID assigned to the layer.
infoTemplateInfoTemplateThe info template for the layer.
labelingInfoLabelClass[]Label definition for this layer, specified as an array of label classes.
layerIdNumberUnique ID of the layer that the FeatureLayer was constructed against.
loadErrorErrorSet if the layer failed to load.
loadedBooleanWhen the layer is loaded, the value becomes "true", and layer properties can be accessed.
maxAllowableOffsetNumberThe maximum allowable offset, only applicable for layers that are not editable.
maxScaleNumberMaximum visible scale for the layer.
maximumTrackPointsNumberThe maximum number of observations being shown for each unique track.
minScaleNumberMinimum visible scale for the layer.
multipatchOptionStringSupports feature services whose data source is a multipatch featureclass.
  • Default is xyFootprint if geometryType is esriGeometryMultiPatch.
nameStringThe name of the layer as defined in the map service.
objectIdFieldStringThe name of the field that contains the Object ID field for the layer.
opacityNumberOpacity or transparency of layer.
purgeIntervalNumberPurge interval of the layer in minutes.
rendererRendererThe renderer for the layer.
showAttributionBooleanWhen true, the layer's attribution is displayed on the map.
showLabelsBooleanDetermines if labels are displayed.
socketObjectRaw access to the connected websocket.
socketUrlStringURL used to make the socket connection.
sourceLayerSourceThe dynamic layer or table source.
stylingBooleanIndicates whether the layer is responsible for styling graphics.
surfaceTypeStringType of vector graphics surface used to draw graphics.
suspendedBooleanWhen true, the layer is suspended.
templatesFeatureTemplate[]An array of feature templates defined in the Feature Service layer.
timeInfoTimeInfoTime information for the layer, such as start time field, end time field, track id field, layers time extent and the draw time interval.
typeStringSpecifies the type of layer.
urlStringURL to the ArcGIS Server REST resource that represents a map service.
versionNumberThe version of ArcGIS Server where the layer is published.
visibleBooleanVisibility of the layer.
visibleAtMapScaleBooleanWhen true, the layer is visible at the current map scale.

Methods

NameReturn typeSummary
add(graphic)GraphicAdds a graphic.
attr(name, value)LayerAdds a new attribute or changes the value of an existing attribute on the layer's node.
clear()NoneClears all graphics.
clearSelection()FeatureLayerClears the current selection.
connect(callback?)NoneConnect to the Stream Server socket.
disableMouseEvents()NoneDisables all mouse events on the graphics layer.
disconnect(callback?)NoneDisconnect from the Stream Server socket.
enableMouseEvents()NoneEnables all mouse events on the graphics layer.
getDefinitionExpression()StringGets the where property of the layer's filter.
getDomain(fieldName, options?)DomainReturns the Domain associated with the given field name.
getField(fieldName)FieldReturns the Field given the specified field name.
getGeometryDefinition()ExtentGets the spatial filter set on the layer.
getLatestObservations()GraphicGets the latest observation for each track in the layer.
getMap()MapReturns reference to the map control the layer is added to.
getNode()HTMLElementReturns the layer's DOM node.
getSelectedFeatures()Graphic[]Gets the currently selected features.
getSelectionSymbol()SymbolGets the current selection symbol.
getTimeDefinition()TimeExtentGet the current time definition applied to the feature layer.
getType(feature)FeatureTypeReturns a FeatureType describing the feature's type.
getUniqueValues(fieldName)Object[]Gets the unique values of the graphics (in the StreamLayer) based on the `fieldName` parameter.
hasXYFootprint()BooleanReturns true if geometryType is esriGeometryMultipatch and multipatchOption is xyFootprint.
hide()NoneSets the visibility of the layer to "false".
isVisibleAtScale(scale)BooleanReturns true if the layer is visible at the given scale.
redraw()NoneRedraws all the graphics in the graphics layer.
refresh()NoneRefreshes the features in the feature layer.
remove(graphic)GraphicRemoves a graphic.
resume()NoneResumes layer drawing.
setDefinitionExpression(expression)FeatureLayerSets the definition expression for the FeatureLayer.
setGeometryDefinition(extent)NoneSets the spatial filter for the layer.
setInfoTemplate(infoTemplate)NoneSpecify or change the info template for a layer.
setLabelingInfo(labelingInfo)NoneSets labeling info on the layer.
setMaxScale(scale)NoneSet the maximum scale for the layer.
setMaximumTrackPoints(value)NoneSets the maximumTrackPoints property for the layer.
setMinScale(scale)NoneSet the minimum scale for the layer.
setOpacity(opacity)NoneInitial opacity or transparency of layer.
setPurgeInterval(interval)LayerChanges the layer's purge interval to the given value (in minutes).
setRenderer(renderer)NoneSet the renderer for the feature layer.
setScaleRange(minScale, maxScale)NoneSet the scale range for the layer.
setSelectionSymbol(symbol)FeatureLayerSets the selection symbol for the feature layer.
setShowLabels(showLabels)NoneSets whether to display labels or not.
setUseMapTime(update)NoneDetermine if the layer will update its content based on the map's current time extent.
setVisibility(isVisible)NoneSets the visibility of the layer.
show()NoneSets the visibility of the layer to "true".
suspend()NoneSuspends layer drawing.
toJson()ObjectReturns an easily serializable object representation of the layer.

Events

[ On Style Events | Connect Style Event ]
All On Style event listeners receive a single event object. Additionally, the event object also contains a 'target' property whose value is the object which fired the event.

Events

NameEvent ObjectSummary
attempt-reconnect
{
  count: <Number>,
  url: <String>
}
Fires when the layer attempts to reconnect to the web socket.
click
{
  event: <Object>
}
Fires when a graphic has been clicked.
connectFires when connection is successfully made to socket.
connection-error
{
  error: <Error>
}
Fires when a connection cannot be made with the web socket.
dbl-click
{
  event: <Object>
}
Fires when a feature has been double clicked.
disconnectFires when disconnect from socket.
error
{
  error: <Error>
}
Fires when there is a problem retrieving a layer.
filter-change
{
  error: <Error>,
  filter: <Object>
}
Fires when the layer receives a message that the server-side filter has been changed.
gdb-version-changeFired when the geodatabase version is switched.
graphic-add
{
  graphic: <Graphic>
}
Fires when a graphic is added to the GraphicsLayer.
graphic-draw
{
  graphic: <Graphic>
}
Fires when a graphic is drawn.
graphic-node-add
{
  graphic: <Graphic>,
  node: <HTMLElement>
}
Fires when a graphic's DOM node is created and added to the layer.
graphic-node-remove
{
  graphic: <Graphic>,
  node: <HTMLElement>
}
This event is fired when a graphic's DOM node is removed (consider the node destroyed).
graphic-remove
{
  graphic: <Graphic>
}
Fires when a graphic is removed from the GraphicsLayer.
graphics-clearFires when all graphics in the GraphicsLayer are cleared.
labeling-info-changeFired when labeling info on the layer changes.
load
{
  layer: <Layer>
}
Fires after layer properties for the layer are successfully populated.
message
{
  message: <Object>
}
Fires after a message is pushed to the layer.
mouse-down<MouseEvent> mouseEventFires when a mouse button is pressed down and the mouse cursor is on a graphic.
mouse-drag<MouseEvent> mouseEventFires while the mouse is being dragged until the mouse button is released.
mouse-move<MouseEvent> mouseEventFires as the mouse moves through a graphic on the GraphicsLayer.
mouse-out<MouseEvent> mouseEventFires as the mouse exits a graphic on the GraphicsLayer.
mouse-over<MouseEvent> mouseEventFires when the mouse first enters into a graphic on the GraphicsLayer.
mouse-up<MouseEvent> mouseEventFires when a mouse button is released and the mouse cursor is on a graphic.
opacity-change
{
  opacity: <Number>
}
Fires when the layer opacity has been changed, and returns an object with the opacity value.
purge-interval-changeFires when the purgeInterval property is changed.
query-ids-complete
{
  objectIds: <Number[]>
}
Fires when queryIds() is complete.
query-limit-exceededFired when the feature layer could not draw all the features due to a maxRecordCount limitation on a query operation.
resumeFires when a layer resumes drawing.
scale-range-changeFires when a layer's minScale and/or maxScale is changed.
scale-visibility-changeFires when a layer's scale visibility changes.
selection-clearFires after clearSelection has been called.
selection-complete
{
  features: <Graphic[]>,
  method: <Number>
}
Fires when selectFeatures() completes.
show-labels-changeFired when the feature layer's labels are changed.
suspendFires when a layer suspends drawing.
update
{
  graphic: <Graphic>
}
Fires any time a layer has finished loading or updating itself.
update-end
{
  error: <Error>,
  info: <Object>,
  relatedFeatureWarning: <String>
}
Fired when the layer has finished updating its content.
update-startFires when layer is added to map (if stream service is associated with an archive feature service) and when graphics are updated on the map due to new ones being added or removed (for example purged).
visibility-change
{
  visible: <Boolean>
}
Fires when the layer visibility has been changed, and returns an object with a Boolean visible property containing the new visibility value of the layer.
Constructor Details

new StreamLayer(url, options?)

Creates a new StreamLayer with a service URL. (Added at v3.7)
Parameters:
<String> url Required URL to an ArcGIS Server Stream Service. Note: Applicable only when layer surfaceType is "svg". For other surface types, this option is ignored.
<Object> options Optional Optional parameters used to create the layer. See options descriptions for further information.
options properties:
<String> className Optional Class attribute to set for the layer's node.
<String> definitionExpression Optional Where clause to use as definition expression for layer. Added at v3.11
<Extent> geometryDefinition Optional The extent to use as the spatial filter for the layer. Added at v3.11
<Number> maximumTrackPoints Optional Maximum number of observations to show for each unique track. Use 0 to show all observations, 1 to only show the most current observation for each track. A trackId field must be specified in the constructor parameters or in the Feature Collection. The default value is 1.
<String[]> outFields Optional An array of strings corresponding with fields to include in the StreamLayer. You can specify ["*"] to fetch values for all fields in the layer.
<Object> purgeOptions Optional Rules for purging data from the layer to avoid overloading the browser with too many features. You can purge based on the number of max features and/or the maximum time that a feature should display on the map. The expiration time is based either on the value of the field specified as the startTime field or the time the message is received. See the object specifications table below for the structure of the purgeOptions object.

When a message is received by the layer, expired features are removed and then features will be removed from the beginning of the graphics array if the total number of graphics in the layer exceeds the displayCount.
purgeOptions: {
  displayCount: 2000,
  age: 2.5
}
Object Specifications:
<purgeOptions>
<Number> age Required The maximum time in minutes that a feature will be displayed. After the time is reached, the feature is removed from the layer. Added at 3.13.
<Number> displayCount Required The maximum number of features the layer will contain.

new StreamLayer(featureCollectionObject, options?)

Creates a new StreamLayer with a FeatureCollection object.
Parameters:
<Object> featureCollectionObject Required A feature collection object. See the object specifications tables below for details.
<Object> options Optional Optional parameters used to create the layer. See options list.
options properties:
<String> className Optional Class attribute to set for the layer's node.
<Extent> geometryDefinition Optional The extent to use as the spatial filter for the layer. Added at v3.11
<Number> maximumTrackPoints Optional Maximum number of observations to show for each unique track. Use 0 to show all observations, 1 to only show the most current observation for each track. A trackId field must be specified in the constructor parameters or in the Feature Collection. The default value is 1.
<String[]> outFields Optional An array of strings corresponding with fields to include in the StreamLayer. You can specify ["*"] to fetch values for all fields in the layer.
<Object> purgeOptions Optional Rules for purging data from the layer to avoid overloading the browser with too many features. You can purge based on the number of max features and/or the maximum time that a feature should display on the map. The expiration time is based either on the value of the field specified as the startTime field or the time the message is received. See the object specifications table below for the structure of the purgeOptions object.

When a message is received by the layer, expired features are removed and then features will be removed from the beginning of the graphics array if the total number of graphics in the layer exceeds the displayCount.
purgeOptions: {
  displayCount: 2000,
  age: 2.5
}
<String> socketUrl Optional The URL to use for connecting to a socket.
Object Specifications:
<featureCollectionObject>
<Object> featureSet Required A collection of features.
<Object> layerDefinition Required The structure is the same as the information returned by REST for a layer in a feature or map service. The minimum layer definition required to create a feature collection object depends on the required functionality, i.e. time, rendering etc.
<purgeOptions>
<NUmber> age Required The maximum time in minutes that a feature will be displayed. After the time is reached, the feature is removed from the layer. Added at 3.13.
<Number> displayCount Required The maximum number of features the layer will contain.
Sample:
require(["esri/layers/StreamLayer", ... ], function(StreamLayer, ... ){
  var layerDefinition = {
    "geometryType": "esriGeometryPoint",
    "fields": [{
      name: "ObjectId",
      type: "esriFieldTypeOID",
      alias: "ObjectId"
    }, {
      name: "AltitudeFeet",
      type: "esriFieldTypeDouble",
      alias: "AltitudeFeet"
    }, {
      name: "ACID",
      type: "esriFieldTypeString",
      alias: "Aircraft ID"
    }]
  };

  var featureCollection = {
    layerDefinition: layerDefinition,
    featureSet: null
  };

  var layer = new StreamLayer(featureCollection, {
    socketUrl: "ws://ec2-54-224-125-57.compute-1.amazonaws.com:8080/faatrackinfo",
    purgeOptions: {
      displayCount: 1000
    }
  };
  ...
});
Property Details

<Object> advancedQueryCapabilities

An object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents. This object contains the existing properties supportsStatistics and supportsAdvancedQueries which is returned in the new supportsOrderBy property. For backward compatibility supportsStatistics and supportsAdvancedQueries will remain properties of FeatureLayer.
"advancedQueryCapabilities" : {
  "supportsPagination" : true, 
  "supportsQueryWithDistance" : true, 
  "supportsReturningQueryExtent" : true, 
  "supportsStatistics" : true, 
  "supportsOrderBy" : true, 
  "supportsDistinct" : true
}
(Added at v3.12)
Sample:
var wildfireResponsePointsFeatureLayer = new FeatureLayer(url, featureLayerOptions);
map.addLayer(wildfireResponsePointsFeatureLayer);

wildfireResponsePointsFeatureLayer.on("load", function featureLayerLoaded(event){
  console.log("advancedQueryCapabilities"),   wildfireResponsePointsFeatureLayer.advancedQueryCapabilities);
  /* Object {supportsStatistics: true, supportsOrderBy: true, supportsDistinct: true} */
});

<Boolean> allowUpdateWithoutMValues

Indicates whether attribute features containing m-values can be edited. (Added at v3.21)
Default value: false

<String> capabilities

Information about the capabilities enabled for this layer.

<String> className

class attribute of the layer's node. (Added at v3.7)

<String> copyright

Copyright information for the layer.

<Credential> credential

Provides credential information for the layer such as userid and token if the layer represents a resource that is secured with token-based authentication. This value is available after the layer has been loaded i.e. layer.loaded is true. (Added at v2.5)

<String | String[]> dataAttributes

List of attribute fields added as custom data attributes to graphics node. Applicable only when layer surfaceType is "svg". (Added at v3.7)

<String> defaultDefinitionExpression

Metadata describing the default definition expression for the layer as defined by the service. The default definition expression limits the features available for display and query. You cannot override this value but you define additional filters on the default expression using the setDefinitionExpression method. For example, if the default definition expression is set to display data where "STATE_NAME = 'California'" you could use setDefinitionExpression to only display a subset of the features in California, for example using "COUNTY='San Diego'".

<Boolean> defaultVisibility

Indicates the default visibility for the layer. (Added at v3.0)
Known values: true | false
Sample:

var isVisible = layer.defaultVisibility;

<String> description

The description of the layer as defined in the map service.

<String> displayField

The name of the layer's primary display field. The value of this property matches the name of one of the fields of the layer.

<Field[]> fields

The array of fields in the layer.

<Extent> fullExtent

The full extent of the layer.

<String> geometryType

Geometry type of the features in the layer. Can be one of the following: "esriGeometryPoint", "esriGeometryPolygon" or "esriGeometryPolyline".

<Graphic[]> graphics

Array of features in the layer.

<String> htmlPopupType

The html popup type defined for the layer. View the constants table for a list of valid values.

<String> id

ID assigned to the layer. If not assigned, esri.Map assigns value. By default, the ID of the layer is "layer" followed by a number. The ID can be user defined only in the layer constructor.
Sample:
  • Setting the layer ID in the layer constructor.
    require([
      "esri/layers/ArcGISDynamicMapServiceLayer", ... 
    ], function(ArcGISDynamicMapServiceLayer, ... ) {
      var population = new ArcGISDynamicMapServiceLayer("http://myserver/arcgis/rest/population/MapServer/Layers", {id:"population"});
      ...
    });
    
  • Setting the layer ID after a layer is initialized.
    population.id = "population";
    
  • Retrieving the layer ID.
    function getMapLayers() {
      for (var j=0, jl=map.layerIds.length; j<jl; j++) {
        var currentLayer = map.getLayer(map.layerIds[j]);
        alert("id: " + currentLayer.id);
      }
    }
    

<InfoTemplate> infoTemplate

The info template for the layer. (Added at v3.9)

<LabelClass[]> labelingInfo

Label definition for this layer, specified as an array of label classes. Use this property to specify any changes to the structure of the label. For example, label expression, placement, and size can be modified and passed to this property. (Added at v3.10)
Sample:
labelingInfo: [{
  "labelExpression": "", //deprecated, labelExpressionInfo property should be used in its place
  "labelExpressionInfo": {
   {"value": "City Of {CITY_NAME} has population {POPULATION}"}
  },
  "useCodedValues":  //parameters used when attribute field has domain values,
  "labelPlacement": "above-right",
  "symbol": {...}, //TextSymbol used for labeling
  "minScale": 0, //specified scale range where labels are visible
  "maxScale": 5000,
  //fieldInfos structure describes attribute field formatting
  "fieldInfos": [
    { fieldName: "created_date", format: { dateFormat: "shortDate"} }, //date/time formatting 
    { fieldName: "last_edited_date", format: { dateFormat: "longDate"} },  //date/time formatting
    { fieldName: "eventtype", format: { places: 6, digitSeparator: true } } //numeric formatting
  ],
  "where": "POP_RANK > 2 AND POP_RANK < 4" //where clause applied on labels
}]

<Number> layerId

Unique ID of the layer that the FeatureLayer was constructed against.

<Error> loadError

Set if the layer failed to load. (Added at v3.9)

<Boolean> loaded

When the layer is loaded, the value becomes "true", and layer properties can be accessed. The onLoad event is also fired.
Known values: true | false

<Number> maxAllowableOffset

The maximum allowable offset, only applicable for layers that are not editable. (Added at v2.7)

<Number> maxScale

Maximum visible scale for the layer. If the map is zoomed in beyond this scale, the layer will not be visible. A value of 0 means the layer does not have a maximum scale. (Added at v3.1)
Default value: 0

<Number> maximumTrackPoints

The maximum number of observations being shown for each unique track. 0 means all observations are being shown; 1 means only the most current, and more than 1 means that the most current is shown plus (maximum - 1) previous observations. (Added at v3.12)

<Number> minScale

Minimum visible scale for the layer. If the map is zoomed out beyond this scale, the layer will not be visible. A value of 0 means the layer does not have a visible scale. (Added at v3.1)
Default value: 0

<String> multipatchOption

Supports feature services whose data source is a multipatch featureclass.
  • Default is xyFootprint if geometryType is esriGeometryMultiPatch. Otherwise, undefined.
  • User can override this property with a different choice in the future when FS supports it.
  • Queries made through the FeatureLayer will include multipatchOption parameter if returnGeometry is true.
  • Applies to snapshot, ondemand, selectFeatures, and queryFeatures
Note: Requires ArcGIS 10.3 and above. (Added at v3.12)
Default value: xyFootprint
Sample:
var infoTemplate = new InfoTemplate("Attributes", "${*}");

var url = "http://servername.fqdn.suffix/arcgis/rest/services/Hosted/pasadena/FeatureServer/0";
var featureLayerOptions = {
  id: "cities",
  mode: FeatureLayer.MODE_AUTO,
  outFields: ["*"],
  infoTemplate: infoTemplate
};
var citiesFeatureLayer = new FeatureLayer(url, featureLayerOptions);

map.addLayer(citiesFeatureLayer);

<String> name

The name of the layer as defined in the map service.

<String> objectIdField

The name of the field that contains the Object ID field for the layer.

<Number> opacity

Opacity or transparency of layer. Values range from 0.0 to 1.0, where 0.0 is 100% transparent and 1.0 has no transparency.
Known values: 0.0 - 1.0
Default value: 1.0

<Number> purgeInterval

Purge interval of the layer in minutes. A value of 0 indicates no purging. Purging of features is done based on the purgeOptions that were supplied when the layer was created. (Added at v3.13)

<Renderer> renderer

The renderer for the layer.

<Boolean> showAttribution

When true, the layer's attribution is displayed on the map. (Added at v3.1)
Known values: true | false
Default value: true

<Boolean> showLabels

Determines if labels are displayed. When false, labels for the layer are not displayed.

If the FeatureLayer has labeling defined on it, labels will automatically display if the Map's showLabels is true.

If you do not wish to have your feature layer label, you can override this behavior by setting its showLabels property to false.

NOTE: In order for the labels to display, all fields used by the labelingInfo should be set in outFields. In addition, only simple labeling is supported, for example {CITY_NAME}. For example, SQL keywords such as "CONCAT" are not supported. Consider using the LabelLayer class where you can specify the textExpression if needing more functionality.
Added at v3.11

Known values: true | false
Default value: true

<Object> socket

Raw access to the connected websocket. A developer can access the websocket to override the websocket's events.

For instance, a developer might want to override the websocket's onmessage event to determine if a new item needs to be added to a unique value renderer before the layer gets refreshed by adding a new feature. This property will be null until the layer is loaded so it should only be accessed after the layer's onLoad event is fired. To see what events a WebSocket fires look at WebSocket.org About WebSockets.

Note: When a developer overrides the onmessage event, it is their responsibility to handle updating the layer with the message. Messages are expected to be in Esri JSON format and a message can contain an array of features.
Sample:
//override websocket onmessage event
layer.on("Connect", function() {
  console.log("CONNECTED SOCKET: ", layer);
  setTimeout(function() {
    layer.socket.onmessage = function(e) {
      //parse json
      var msgarray = JSON.parse(e.data);
      msgarray = Array.isArray(msgarray) ? msgarray : [msgarray];
      for (var i = 0; i < msgarray.length; i++){
        //make graphic
        var jsonFeature = msgarray[i];
        var graphic = new Graphic();
        var geom = jsonUtils.fromJson(jsonFeature.geometry);
        graphic.setGeometry(geom);
        graphic.setAttributes(jsonFeature.attributes);
        graphic.setSymbol(sym);
        layer.add(graphic);
      }
    };
  }, 25);
});

<String> socketUrl

URL used to make the socket connection. Read-only.

<LayerSource> source

The dynamic layer or table source. (Added at v2.7)

<Boolean> styling

Indicates whether the layer is responsible for styling graphics. When true, styling is based on graphics symbol or the layer's renderer. When false, graphics styling is disabled. Applicable only when layer surfaceType is "svg". (Added at v3.7)
Known values: true | false

<String> surfaceType

Type of vector graphics surface used to draw graphics. (Added at v3.7)
Known values: "svg" | "canvas-2d" | "vml"
Default value: "svg" on all browsers - except IE8 or earlier where "vml" is used to draw graphics.

<Boolean> suspended

When true, the layer is suspended. A layer is considered to be suspended when one of the following is true:
  • The layer is hidden.
  • The layer is not visible at the current map scale.
  • The layer is explicitly suspended by calling the Layer.suspend method.
(Added at v3.1)
Known values: true | false

<FeatureTemplate[]> templates

An array of feature templates defined in the Feature Service layer. Only applicable for ArcGIS Server Feature Service layers.
Sample:
require([
  "esri/layers/FeatureLayer", "dojo/_base/array", ... 
], function(FeatureLayer, array, ... ) {
  var layer = new FeatureLayer( ... );
  var templates = layer.templates;
  array.forEach(templates,function(template){
    console.log(template.description);
    console.log(template.name);
  });
  ...
});

<TimeInfo> timeInfo

Time information for the layer, such as start time field, end time field, track id field, layers time extent and the draw time interval. Only applicable if the layer is time aware.

<String> type

Specifies the type of layer. Can be "Feature Layer" or "Table".

<String> url

URL to the ArcGIS Server REST resource that represents a map service. To obtain the URL, use Services Directory. An example URL for the Street Map service on ArcGIS Online is:
http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer. (Added at v1.2)

<Number> version

The version of ArcGIS Server where the layer is published. Examples are 9.3, 9.31, 10. (Added at v2.1)

<Boolean> visible

Visibility of the layer.
Known values: true | false
Default value: true

<Boolean> visibleAtMapScale

When true, the layer is visible at the current map scale. (Added at v3.1)
Known values: true | false
Method Details

add(graphic)

Adds a graphic.
Return type: Graphic
Parameters:
<Graphic> graphic Required The graphic to add.
Sample:
require([
  "esri/symbols/SimpleFillSymbol", "esri/graphic", ... 
], function(SimpleFillSymbol, Graphic, ... ) {
  function addGraphic(geometry) {
    var symbol = new SimpleFillSymbol();
    graphicsLayer.add(new Graphic(geometry, symbol));
  }
  ...
});

attr(name, value)

Adds a new attribute or changes the value of an existing attribute on the layer's node. Removes the attribute if the value is null or undefined. (Added at v3.7)
Return type: Layer
Parameters:
<String> name Required The name of the attribute.
<String> value Required The value of the attribute. Set this value as null to remove the attribute.

clear()

Clears all graphics.
Sample:

graphicsLayer.clear();

clearSelection()

Clears the current selection.
Return type: FeatureLayer

connect(callback?)

Connect to the Stream Server socket. This method is called internally with the provided socketUrl in the constructor. Triggers the onConnect event.
Parameters:
<Function> callback Optional The function to call when the method has completed.

disableMouseEvents()

Disables all mouse events on the graphics layer.

disconnect(callback?)

Disconnect from the Stream Server socket. Triggers the onDisconnect event.
Parameters:
<Function> callback Optional The function to call when the method has completed.

enableMouseEvents()

Enables all mouse events on the graphics layer.

getDefinitionExpression()

Gets the where property of the layer's filter. Only relevant when data for the layer is coming from an ArcGIS Server Stream Service. (Added at v3.11)
Return type: String

getDomain(fieldName, options?)

Returns the Domain associated with the given field name. This being either a Coded Value Domain or Range Domain. (Added at v3.12)
Return type: Domain
Parameters:
<String> fieldName Required Name of the attribute field.
<Object> options Optional Please see the options object specification table below.
Object Specifications:
<options>
<Graphic> feature Required The feature in which the Domain is retrieved.
NOTE: If the layer has sub-types, the domain will be calculated based on the feature type and domain defined for that type.

getField(fieldName)

Returns the Field given the specified field name. (Added at v3.12)
Return type: Field
Parameters:
<String> fieldName Required Name of the attribute field.

getGeometryDefinition()

Gets the spatial filter set on the layer. (Added at v3.11)
Return type: Extent

getLatestObservations()

Gets the latest observation for each track in the layer. If the layer does not have a "trackId" field set, then all the graphics in the layer are returned. (Added at v3.14)
Return type: Graphic

getMap()

Returns reference to the map control the layer is added to. Returns null or undefined if it is not added to a map. (Added at v3.7)
Return type: Map

getNode()

Returns the layer's DOM node. (Added at v3.7)
Return type: HTMLElement

getSelectedFeatures()

Gets the currently selected features.
Return type: Graphic[]

getSelectionSymbol()

Gets the current selection symbol.
Return type: Symbol

getTimeDefinition()

Get the current time definition applied to the feature layer.
Return type: TimeExtent
Sample:
require([
  "esri/map", "esri/layers/FeatureLayer", "esri/layers/TimeInfo", ... 
], function(Map, FeatureLayer, TimeInfo, ... ) {
  var timeSlider = new TimeSlider( ... );
  var featureLayer = new FeatureLayer();
  timeSlider.createTimeStopsByTimeInterval(featureLayer.getTimeDefinition(), 
    1, TimeInfo.UNIT_HOURS);
  ...
});

getType(feature)

Returns a FeatureType describing the feature's type.
NOTE: This is applicable if the layer containing the feature has a TypeIdField. (Added at v3.12)
Return type: FeatureType
Parameters:
<Graphic> feature Required A feature from this layer.

getUniqueValues(fieldName)

Gets the unique values of the graphics (in the StreamLayer) based on the `fieldName` parameter. The return array of unique values is sorted in ascending order. An empty array is returned if no `fieldName` parameter is supplied or if the field does not exist in the layer. (Added at v3.12)
Return type: Object[]
Parameters:
<String> fieldName Required Field to get the unique values from.

hasXYFootprint()

Returns true if geometryType is esriGeometryMultipatch and multipatchOption is xyFootprint. When true, the FeatureLayer will behave as if it were a polygon.
  • Auto generalization will be enabled by default.
  • Auto mode will treat the layer like a polygon layer.
(Added at v3.12)
Return type: Boolean
Sample:
citiesFeatureLayer.on("load", function featureLayerLoaded(event){
  var hasXYFootprint = citiesFeatureLayer.hasXYFootprint();
  console.log("Contains xyfootprints:", hasXYFootprint);
});

hide()

Sets the visibility of the layer to "false". The layer is not removed, but it is hidden from view.

isVisibleAtScale(scale)

Returns true if the layer is visible at the given scale. (Added at v3.1)
Return type: Boolean
Parameters:
<Number> scale Required The scale at which to check if the layer is visible.

redraw()

Redraws all the graphics in the graphics layer. Unlike refresh(), redraw does not re-query features from the server. (Added at v3.3)

refresh()

Refreshes the features in the feature layer. The feature layer requeries all the features in the service, except the selected features, and updates itself.

remove(graphic)

Removes a graphic.
Return type: Graphic
Parameters:
<Graphic> graphic Required The graphic to remove.

resume()

Resumes layer drawing. (Added at v3.1)

setDefinitionExpression(expression)

Sets the definition expression for the FeatureLayer. Only the features that match the definition expression are displayed. A definition expression limits the features available for display and queries by applying constraints to the layer's attribute fields. Setting a definition expression is useful when the dataset is large and you don't want to bring everything to the client for analysis. This method is typically called before adding the layer to the map. If the method is called after the layer is added to the map the layer will refresh itself to reflect the new definition expression.

This definition expression is combined with the layer's default definition expression which results in a further restriction of the layer.

Return type: FeatureLayer
Parameters:
<String> expression Required The definition expression to apply. For example, "TYPE='Park'"
Sample:
featureLayer.setDefinitionExpression("STATE_NAME = 'South Carolina'");

setGeometryDefinition(extent)

Sets the spatial filter for the layer. (Added at v3.11)
Parameters:
<Extent> extent Required Limit the features in the StreamLayer by setting a bounding box.

setInfoTemplate(infoTemplate)

Specify or change the info template for a layer. (Added at v2.2)
Parameters:
<InfoTemplate> infoTemplate Required The new info template.
Sample:
require([
  "esri/InfoTemplate", ... 
], function(InfoTemplate, ... ) {
    var template = new InfoTemplate();

    template.setTitle("${qAddress}");

    template.setContent(getTextContent);

    featureLayer.setInfoTemplate(template);
  ...
});

setLabelingInfo(labelingInfo)

Sets labeling info on the layer. Input value is an array of LabelClass objects. (Added at v3.10)
Parameters:
<LabelClass[]> labelingInfo Required This is the label definition for this layer, specified as an array of label classes. Use this property to specify any changes to the structure of the label. For example, label expression, placement, and size can be modified and passed to this property.
Sample:
//make sure the Map's showLabels option is set to true
  var map = new Map("map", {
    basemap: "streets",
    center:[-80, 30],
    zoom: 5,
    showLabels : true
  });
 
//create featurelayer
  var flayer = new FeatureLayer(url, {
    outFields: ["*"] //make sure field to label is specified here in outFields
  });


//create a text symbol and renderer to define the style of labels
   var labelSymbol = new TextSymbol(); 
   var labelRenderer = new SimpleRenderer(labelSymbol);


var json = {
  "labelExpressionInfo": {"value": "{LocalTime}"},
  "useCodedValues": false,
  "labelPlacement":"above-right",
  "fieldInfos": [{fieldName: "LocalTime",format: { "dateFormat": "shortDate"}}]
  };

//create instance of LabelClass
  var lc = new LabelClass(json);
  lc.symbol = labelSymbol; // symbol also can be set in LabelClass' json
  flayer.setLabelingInfo([ lc ]);

setMaxScale(scale)

Set the maximum scale for the layer. (Added at v3.1)
Parameters:
<Number> scale Required The maximum scale at which the layer is visible.

setMaximumTrackPoints(value)

Sets the maximumTrackPoints property for the layer. (Added at v3.11)
Parameters:
<Number> value Required The maximum track points for the layer.

setMinScale(scale)

Set the minimum scale for the layer. (Added at v3.1)
Parameters:
<Number> scale Required The minimum scale at which the layer is visible.

setOpacity(opacity)

Initial opacity or transparency of layer. Not supported in Internet Explorer.
Parameters:
<Number> opacity Required Value from 0 to 1, where 0 is 100% transparent and 1 has no transparency. The default value is 1.
Sample:
featureLayer.setOpacity(.50);

setPurgeInterval(interval)

Changes the layer's purge interval to the given value (in minutes). A value of 0 stops purging. (Added at v3.13)
Return type: Layer
Parameters:
<Number> interval Required The purge interval in minutes.

setRenderer(renderer)

Set the renderer for the feature layer.
Parameters:
<Renderer> renderer Required The renderer to apply to the feature layer
Sample:
require([
  "esri/symbols/SimpleFillSymbol", "esri/Color", "esri/renderers/SimpleRenderer", ... 
], function(SimpleFillSymbol, Color, SimpleRenderer, ... ) {
  var symbol = new SimpleFillSymbol().setColor(new Color([255,0,0,0.5]));

  var renderer = new SimpleRenderer(symbol);

  featureLayer.setRenderer(renderer);
  ...
});

setScaleRange(minScale, maxScale)

Set the scale range for the layer. If minScale and maxScale are set to 0 then the layer will be visible at all scales. (Added at v2.5)
Parameters:
<Number> minScale Required The minimum scale for the layer. If the map is zoomed out beyond the specified scale the layer will not be visible. A value of 0 means the layer does not have a minimum scale.
<Number> maxScale Required The maximum scale for the layer. If the map is zoomed out beyond the specified scale the layer will not be visible. A value of 0 means the layer does not have a maximum scale.
Sample:

featureLayer.setScaleRange(591657528,147914381);

setSelectionSymbol(symbol)

Sets the selection symbol for the feature layer. If no symbol is specified, features are drawn using the layer's renderer.
Return type: FeatureLayer
Parameters:
<Symbol> symbol Required Symbol for the current selection. Make sure the symbol type is appropriate for the geometry type of the layer.
Sample:
require([
  "esri/layers/FeatureLayer", "esri/symbols/SimpleFillSymbol", "esri/Color", ... 
], function(FeatureLayer, SimpleFillSymbol, Color, ... ) {
  var featureLayer = new FeatureLayer( ... );
  var selectionSymbol = new SimpleFillSymbol().setColor(new Color([255,255,0,0.5]));
  featureLayer.setSelectionSymbol(selectionSymbol);
  ...
});

setShowLabels(showLabels)

Sets whether to display labels or not. Set to false to turn off labeling. (Added at v3.11)
Parameters:
<Boolean> showLabels Required Set to true to show labels.

setUseMapTime(update)

Determine if the layer will update its content based on the map's current time extent. Default value is true. (Added at v2.2)
Parameters:
<Boolean> update Required When false the layer will not update its content based on the map's time extent. Default value is true.

setVisibility(isVisible)

Sets the visibility of the layer. When true, the layer is visible.
Parameters:
<Boolean> isVisible Required Set the visibility of the layer.

show()

Sets the visibility of the layer to "true".

suspend()

Suspends layer drawing. (Added at v3.1)

toJson()

Returns an easily serializable object representation of the layer. Regardless of the layer's mode of operation, only features currently available on the client are included.


{

  layerDefinition: <Object>,

    featureSet: {

    features:<Object[]>

  }

}

Return type: Object
Event Details
[ On Style Events | Connect Style Event ]

attempt-reconnect

Fires when the layer attempts to reconnect to the web socket. (Added at v3.11)
Event Object Properties:
<Number> count Number of connection attempts made.
<String> url Web socket URL being used for attempting to connect.

click

Fires when a graphic has been clicked. Should be used in favor of onClick. (Added at v3.5)
Event Object Properties:
<Object> event The returned object contains screenPoint, mapPoint, and Graphic.

connect

Fires when connection is successfully made to socket.

connection-error

Fires when a connection cannot be made with the web socket. (Added at v3.11)
Event Object Properties:
<Error> error Error message returned in a JavaScript error object.

dbl-click

Fires when a feature has been double clicked. (Added at v3.6)
Event Object Properties:
<Object> event The returned object contains screenPoint, mapPoint, and graphic.
Sample:
require([
  "dojo/_base/connect", "esri/toolbars/Edit", ... 
], function(connect, Edit, ... ) {
  var editToolbar = new Edit( ... );
  connect.connect(firePerimeterFL, "onDblClick", function(evt) {
    editToolbar.activate(Edit.EDIT_VERTICES , evt.graphic);
  });
  ...
});

disconnect

Fires when disconnect from socket.

error

Fires when there is a problem retrieving a layer. Should be used in favor of onError. (Added at v3.5)
Event Object Properties:
<Error> error ArcGIS Server error message returned in a JavaScript error object.

filter-change

Fires when the layer receives a message that the server-side filter has been changed. (Added at v3.11)
Event Object Properties:
<Error> error An optional parameter whose value will be a standard JavaScript Error object if an error occurred.
<Object> filter Current server-side filter, an object with "geometry" and "where" as in {geometry: esri.geometry.Extent, where: String}.

gdb-version-change

Fired when the geodatabase version is switched. (Added at v3.5)

graphic-add

Fires when a graphic is added to the GraphicsLayer. Should be used in favor of onGraphicAdd. (Added at v3.5)
Event Object Properties:
<Graphic> graphic The added graphic.

graphic-draw

Fires when a graphic is drawn. A graphic is drawn or redrawn when:
  • When it is added to the layer.
  • When Geometry or Symbol is modified.
  • When it enters the viewport and intersects the map extent.
  • When the layer is redrawn.
(Added at v3.7)
Event Object Properties:
<Graphic> graphic Graphic being drawn. When the layer surfaceType is "svg" or "vml", the graphic's DOM node is accessible with graphic.getNode().

graphic-node-add

Fires when a graphic's DOM node is created and added to the layer. Fires only when the layer surfaceType is "svg" or "vml". (Added at v3.7)
Event Object Properties:
<Graphic> graphic Graphic being drawn.
<HTMLElement> node Graphic's DOM node.

graphic-node-remove

This event is fired when a graphic's DOM node is removed (consider the node destroyed). The DOM node of a graphic is removed when:
  • Graphic is removed from the layer.
  • Graphic exits the viewport on map navigation.
  • When a symbol change cannot be applied to the Graphic without replacing the current node with a new one. For example: when a marker symbol is changed from SimpleMarkerSymbol to PictureMarkerSymbol, onGraphicNodeRemove will be fired for the node that is being replaced (SVG Circle) and onGraphicNodeAdd will be fired for the new node (SVG Image).
Fires only when the layer surfaceType is "svg" or "vml". (Added at v3.7)
Event Object Properties:
<Graphic> graphic Graphic being drawn.
<HTMLElement> node Graphic's DOM node.

graphic-remove

Fires when a graphic is removed from the GraphicsLayer. Should be used in favor of onGraphicRemove. (Added at v3.5)
Event Object Properties:
<Graphic> graphic The removed graphic.

graphics-clear

Fires when all graphics in the GraphicsLayer are cleared. Should be used in favor of onGraphicsClear. (Added at v3.5)

labeling-info-change

Fired when labeling info on the layer changes. (Added at v3.10)

load

Fires after layer properties for the layer are successfully populated. This event must be successful before the layer can be added to the map. Should be used in favor of onLoad. (Added at v3.5)
Event Object Properties:
<Layer> layer The loaded layer.

message

Fires after a message is pushed to the layer. This event is fired before the message has affected the layer's graphics.
Event Object Properties:
<Object> message The message object. It can be of type "create", "delete", or "update".

mouse-down

Fires when a mouse button is pressed down and the mouse cursor is on a graphic. Should be used in favor of onMouseDown. (Added at v3.5)
Event Object:
<MouseEvent> mouseEvent A standard DOM MouseEvent with additional properties mapPoint and screenPoint.

mouse-drag

Fires while the mouse is being dragged until the mouse button is released. Should be used in favor of onMouseDrag. (Added at v3.5)
Event Object:
<MouseEvent> mouseEvent A standard DOM MouseEvent with additional properties mapPoint and screenPoint.

mouse-move

Fires as the mouse moves through a graphic on the GraphicsLayer. Should be used in favor of onMouseMove. (Added at v3.5)
Event Object:
<MouseEvent> mouseEvent A standard DOM MouseEvent with additional properties mapPoint and screenPoint.

mouse-out

Fires as the mouse exits a graphic on the GraphicsLayer. Should be used in favor of onMouseOut. (Added at v3.5)
Event Object:
<MouseEvent> mouseEvent A standard DOM MouseEvent with additional properties mapPoint and screenPoint.

mouse-over

Fires when the mouse first enters into a graphic on the GraphicsLayer. Should be used in favor of onMouseOver. (Added at v3.5)
Event Object:
<MouseEvent> mouseEvent A standard DOM MouseEvent with additional properties mapPoint and screenPoint.

mouse-up

Fires when a mouse button is released and the mouse cursor is on a graphic. Should be used in favor of onMouseUp. (Added at v3.5)
Event Object:
<MouseEvent> mouseEvent A standard DOM MouseEvent with additional properties mapPoint and screenPoint.

opacity-change

Fires when the layer opacity has been changed, and returns an object with the opacity value. Should be used in favor of onOpacityChange. (Added at v3.5)
Event Object Properties:
<Number> opacity Fires when the layer opacity (transparency) changes. A number property named opacity that indicates the new opacity. Values range from 0.0 to 1.0, where 0.0 is 100% transparent and 1.0 has no transparency.

purge-interval-change

Fires when the purgeInterval property is changed. (Added at v3.13)

query-ids-complete

Fires when queryIds() is complete. Should be used in favor of onQueryIdsComplete. (Added at v3.5)
Event Object Properties:
<Number[]> objectIds Array of ObjectIds returned from the query.

query-limit-exceeded

Fired when the feature layer could not draw all the features due to a maxRecordCount limitation on a query operation. Should be used in favor of onQueryLimitExceeded. (Added at v3.5)

resume

Fires when a layer resumes drawing. (Added at v3.6)

scale-range-change

Fires when a layer's minScale and/or maxScale is changed. Should be used in favor of onScaleRangeChange. (Added at v3.5)

scale-visibility-change

Fires when a layer's scale visibility changes. The scale visibility changes when a layer is initially visible and becomes invisible because the map scale does not intersect the layer's scale range or vice versa. Should be used in favor of onScaleVisibilityChange. (Added at v3.5)

selection-clear

Fires after clearSelection has been called. Should be used in favor of onSelectionClear. (Added at v3.5)

selection-complete

Fires when selectFeatures() completes. Should be used in favor of onSelectionComplete. (Added at v3.5)
Event Object Properties:
<Graphic[]> features Features returned from the query. This does not equal the current selection, call getSelectedFeatures() to retrieve the current selection set.
<Number> method Selection method used in the selectFeatures method.

show-labels-change

Fired when the feature layer's labels are changed. Should be used in favor of onShowLabelsChange. (Added at v3.11)

suspend

Fires when a layer suspends drawing. (Added at v3.6)

update

Fires any time a layer has finished loading or updating itself. For an ArcGISTiledMapServiceLayer, the event fires when all required tiles have been retrieved and displayed. For an ArcGISDynamicMapServiceLayer or ArcGISImageServiceLayer, the event fires when the map image has been retrieved and displayed. For a GraphicsLayer, the event fires when all graphics have been redrawn after a pan or zoom. Deprecated at v2.0. Use update-start and update-end instead. (Added at v3.6)
Event Object Properties:
<Graphic> graphic The graphic that was added, updated, or removed from the layer.

update-end

Fired when the layer has finished updating its content. This event is always preceded by update-start. Should be used in favor of onUpdateEnd. (Added at v3.5)
Event Object Properties:
<Error> error Optional argument available when an error occurs during the update.
<Object> info Optional object that may have a boolean queryLimitExceeded property. queryLimitExceeded will be true if the feature layer could not draw all features due to a maxRecordCount limitation on the query operation. As of v2.8
<String> relatedFeatureWarning (Added at 3.15), optional argument describing if a filter could not be applied to a feature or map service with features related to the stream service. Message reads, "Querying related feature service using the current filter failed. All related features are displayed, and the filter is applied to the stream service only."

update-start

Fires when layer is added to map (if stream service is associated with an archive feature service) and when graphics are updated on the map due to new ones being added or removed (for example purged). (Added at v3.11)

visibility-change

Fires when the layer visibility has been changed, and returns an object with a Boolean visible property containing the new visibility value of the layer. Should be used in favor of onVisibilityChange. (Added at v3.5)
Event Object Properties:
<Boolean> visible Fires when the layer visibility changes. A boolean property named visible indicates whether or not the layer is visible after visibility changed.