English

How To: Query features and zoom to the extent of all features in ArcGIS API for JavaScript

Summary

In some instances, the Extent.union() method is required to join multiple extents to form one large single extent. The instructions provided describe how to query features and zoom to the extent of all features using JavaScript.

Procedure

For point features, the value of the minimum and maximum x and y coordinates may be absent. Use the following script to set the full extent for point features:

var i, gra; 

if(results.features[0].geometry.type == "point"){ 
map.graphics.clear(); 

// for xmax and xmin etc. 
var xmin = results.features[0].geometry.x; 
var xmax = results.features[0].geometry.x; 
var ymax = results.features[0].geometry.y; 
var ymin = results.features[0].geometry.y; 

newExtent = new Extent(xmin, ymin, xmax, ymax, results.features[0].geometry.spatialReference); 

for (i = 1; i < results.features.length; i++) { 
gra = results.features[i]; 
var xmini = results.features[i].geometry.x; 
var xmaxi = results.features[i].geometry.x; 
var ymaxi = results.features[i].geometry.y; 
var ymini = results.features[i].geometry.y; 


thisExtent = new Extent(xmini, ymini, xmaxi, ymaxi, results.features[0].geometry.spatialReference); 
// making a union of extent or previous feature and current feature. 
newExtent = newExtent.union(thisExtent); 

gra.setSymbol(sms); 
gra.setInfoTemplate(popupTemplate); 
map.graphics.add(gra); 
} 

map.setExtent(newExtent); 
}

For polygon features, the script can be shortened due to the feature having its own geometry. Use the following script to set the full extent for polygon features.

if (results.features[0].geometry.type == "line" || results.features[0].geometry.type == "polygon"){ 
//clearing any graphics if present. 
map.graphics.clear(); 
newExtent = new Extent(results.features[0].geometry.getExtent()) 
for (i = 0; i < results.features.length; i++) { 
var graphic = results.features[i]; 
var thisExtent = graphic.geometry.getExtent(); 

// making a union of extent or previous feature and current feature. 
newExtent = newExtent.union(thisExtent); 
graphic.setSymbol(sfs); 
graphic.setInfoTemplate(popupTemplate); 
map.graphics.add(graphic); 
} 
map.setExtent(newExtent); 
}
Note:
Both of the scripts can be combined to check for and use both point and polygon features. Add the statement 'else' in front of the second starting 'if' point. For example: 

else if (results.features[0].geometry.type == "line" || results.features[0].geometry.type == "polygon")

Related Information