Skip to content

Extending the ArcGIS Server JavaScript API to Find Graphics

October 6, 2009

Currently, to my knowledge, the ArcGIS Server JavaScript API offers no way to easily locate a graphic, or graphics without writing your own for loop that compares keys and values. Using the prototype, we can extend the esri.GraphicsLayer class to provide a function to search for graphics holding the value of an attribute.

esri.layers.GraphicsLayer.prototype.find = function(value, attribute) {
  var matches = [];
  var re = new RegExp(value);
  for(var graphic in this.graphics) {
    var g = this.graphics[graphic];
    if(typeof(g.attributes[attribute]) !== "undefined") /* ignore when attribute is undefined */
      if(g.attributes[attribute].search(re) > -1)
        matches.push(g);
  };
  return matches;
};

Now, we can find all the graphics where the specified attribute contains text or a regular expression. For example, using the Firebug console, we can mess with the Points in Extent sample by running the esri.layers.GraphicsLayer.find extension and testing out the function.

var attributeName = "CITY_NAME";
var value = /l{2}/;
var graphics = map.graphics.find(value, attributeName);
for(var g in graphics)
  console.log(graphics[g].attributes[attributeName]);

We get, or should get (assuming ESRI hasn’t changed anything) the following:

  • Bellingham
  • North Marysville
  • Marysville
  • Alderwood Manor-Bothell North
  • Bothell
  • Woodinville
  • Inglewood-Finn Hill
  • Bellevue
  • Newport Hills
  • East Hill-Meridian
  • Puyallup
  • South Hill
  • Ellensburg
  • Pullman
  • Walla Walla

The JavaScript API is very powerful and continues to become more so. However, there are plenty of features that are lacking to make things easier for a developer. Watch for more ways to extend the API in the future.

About these ads
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: