ArcGIS API for JavaScript

Looping through graphics using the ArcGIS API for JavaScript

When working with the ArcGIS API for JavaScript you’ll often find yourself looping through arrays, like the collection of graphics stored in a graphics layer or the results of a QueryTask. In this post we’ll explore two approaches for looping through arrays; using a standard for loop and working with a dojo implementation of one of the JavaScript Array Extras.

For Loop

First lets look at using a for loop to add query task results to a map. The results of QueryTask are returned as an array of Graphic features so we can use a for loop to iterate through the task results and add each graphic to the map.

 dojo.connect(queryTask,"onComplete",function(featureSet){
   for(var i=0; i < featureSet.features.length; i++){
     map.graphics.add(featureSet.features[i]);
   })

We can optimize the code a bit by storing the length of the array in a variable. Then the length of the array doesn’t need to be recalculated on each loop. The stored length (il) is just compared to the value of the counter(i).

 for (var i=0; il = featureSet.features.length; i < il; i++){

JavaScript Array Extras

The JavaScript array extras are useful functions for working with arrays and are part of ECMAScript 5th Edition, the next revision of the standards on which JavaScript is based. The revised standard is still under development so not all browsers support this functionality. Thankfully Dojo has implemented similar functions as part of Dojo Core so we can take advantage of one of the array extras, dojo.forEach, to simplify the process of looping through an array of graphics. Dojo.forEach runs a function on each item in the array.

 dojo.connect(queryTask,"onComplete",function(featureSet){
   dojo.forEach (featureSet.features, function(feature) {
     map.graphics.add(feature);
   });
 });

Note that we no longer need the counter and array length variable which makes the code easier to read and can help avoid the following problems:

If you do need access to the iterator you can specify an additional argument to the function. This argument provides access to the current position in the array.

 dojo.forEach(featureSet.features,function(feature,index){
   //do something with the index here
 }

Links

Contributed by Kelly Hutchins of the ArcGIS JavaScript API development team

Next Article

Make This Dymaxion Globe Ornament Please

Read this article