Extending the ArcGIS Server JavaScript API to Find Graphics
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:
BellinghamNorth MarysvilleMarysvilleAlderwood Manor-Bothell NorthBothellWoodinvilleInglewood-Finn HillBellevueNewport HillsEast Hill-MeridianPuyallupSouth HillEllensburgPullmanWalla 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.