Friday, September 20, 2019

How to use FeatureLayer in ArcGIS API for JavaScript 3.x

In this post we will explain how to use FeatureLayer class in ArcGIS API for JavaScript.

applies to 3.x API
First we need to include (Map, FeatureLayer) classes from the API


require([
  "esri/map",
  "esri/layers/FeatureLayer",
  "dojo/ready",
], function(Map, FeatureLayer, ready) {

  ready(function(){
    // Put your code in this block.
  });
});

Also note that we used the ready class from dojo in order to run our code after the page is fully loaded.

Now we need to create a new object of type FeatureLayer. We do that in the "ready" function as follows:
ready(function(){
    var feature_layer = new FeatureLayer();
});

To properly creating an object of FeatureLayer, we need to pass some properties to its constructor
ready(function(){
  var feature_layer = new FeatureLayer(
    url_to_feature_layer
    , {
      mode: FeatureLayer.MODE_ONDEMAND,
      outFields: ["*"],
      visible: true,
      id: "id_inside_map"
    }
  );
});

Let us explain the properties:
  • url_to_feature_layer : The url of the FeatureLayer for example this is a URL from ESR:
    https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Prominent_Peaks_attach/FeatureServer/0
  • mode: The mode to load features:
    MODE_ONDEMAND: Loads features when you pan to the extent in which they exist or when you zoom to the level in which the layer is visible.
    MODE_SNAPSHOT: The features will be loaded once the layer is added to the map.
    MODE_SELECTION: The feature will be loaded once it is selected using the "selectFeatures" method.
    MODE_AUTO: The mode will be selected automatically depending on the number of features and the number of vertices in the features.
  • visible: Determines if the layer is visible in the map or not (the default value is true).
  • id: The ID of the layer in the map, this helps you to retrieve the layer from the map in a user friendly name.
 Now we need to add the FeatureLayer to the map:
ready(function(){
  var feature_layer = new FeatureLayer(
    url_to_feature_layer
    , {
      mode: FeatureLayer.MODE_ONDEMAND,
      outFields: ["*"],
      visible: true,
      id: "id_inside_map"
    }
  );
 map.addLayer(feature_layer);
});

Thanks for reading my tutorial, please do not hesitate to ask any question in the comments.

No comments:

Post a Comment