Query Task

Download Sample Application

This sample shows you how to perform attribute and spatial queries on a feature layer using a query task. Locate a state in the USA by entering a state name (or part of a State name e.g. ‘New’) in the search control and press enter. Upon successful completion of the attribute query the delegate ‘didExecuteWithFeatureSetResult’ method will return a feature set that is used to populate a table view. Select a state from the list and the map will zoom to the selected feature.

//header file
@interface QueryTaskSample : NSViewController <AGSQueryTaskDelegate>
@property (strong) AGSQueryTask *queryTask;
@property (strong) AGSQuery *query;
@property (strong) AGSFeatureSet *featureSet;
...
@end

//implementation file

//setup query task against layer, specify the delegate
self.queryTask = [AGSQueryTask queryTaskWithURL:[NSURL URLWithString:@"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"]];
self.queryTask.delegate = self;
	
//setup query
self.query = [AGSQuery query];
self.query.outFields = [NSArray arrayWithObjects:@"*", nil];
self.query.returnGeometry = TRUE;
  
//get search string and execute query
self.query.text = "Carolina";
self.query.outSpatialReference = self.mapView.spatialReference;
[self.queryTask executeWithQuery:self.query];

- (void)queryTask:(AGSQueryTask *)queryTask operation:(NSOperation *)op didExecuteWithFeatureSetResult:(AGSFeatureSet *)featureSet {
  //process the featureSet
  ...
}

Sample Code

//SWIFT SAMPLE CODE
/*
Copyright 2014 Esri

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Cocoa
import ArcGIS

//layer urls
let kQTBaseMapURL = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"
let kQTDynamicMapServiceURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer"
let kStatesURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"

class QueryTaskSwiftSample: NSViewController, AGSQueryTaskDelegate, NSTableViewDelegate, NSTableViewDataSource, NSSplitViewDelegate {
    
    @IBOutlet weak var mapView:AGSMapView!
    @IBOutlet weak var searchField:NSSearchField!
    @IBOutlet weak var tableView:NSTableView!
    var graphicsLayer:AGSGraphicsLayer!
    var queryTask:AGSQueryTask!
    var query:AGSQuery!
    var featureSet:AGSFeatureSet!
    var envelope:AGSEnvelope!
    
    //MARK: - awakeFromNib
    
    // -------------------------------------------------------------------------------
    //  awakeFromNib
    // -------------------------------------------------------------------------------
    override func awakeFromNib() {
    
        //add base layer to map
        let baseMapLayer = AGSTiledMapServiceLayer(URL: NSURL(string: kQTBaseMapURL))
        self.mapView.addMapLayer(baseMapLayer, withName:"Base Layer")
        
        //add dynamic layer to map
        //set visible layers
        let dynamicLayer = AGSDynamicMapServiceLayer(URL: NSURL(string: kQTDynamicMapServiceURL))
        dynamicLayer.visibleLayers = ["5"]
        self.mapView.addMapLayer(dynamicLayer, withName:"US States")
        
        //create simple fill symbol for graphic layer's renderer
        let sfs = AGSSimpleFillSymbol()
        sfs.color = NSColor.greenColor().colorWithAlphaComponent(0.5)
        sfs.outline.color = NSColor(red: 0, green:128, blue:0, alpha:1.0)
        sfs.outline.width = 4
        
        //add graphics layer to map
        //set simple renderer
        self.graphicsLayer = AGSGraphicsLayer()
        self.graphicsLayer.renderer = AGSSimpleRenderer(symbol: sfs)
        self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer")
        
        //setup query task against layer, specify the delegate
        self.queryTask = AGSQueryTask(URL: NSURL(string: kStatesURL))
        self.queryTask.delegate = self
        
        //setup query
        self.query = AGSQuery()
        self.query.outFields = ["*"]
        self.query.returnGeometry = true
        
        //zoom to predefined extend with known spatial reference of the map
        self.envelope = AGSEnvelope(xmin: -19749568.092138, ymin:2466036.346731, xmax:-6534031.777518, ymax:11595745.868985, spatialReference:AGSSpatialReference.webMercatorSpatialReference())
        self.mapView.zoomToEnvelope(self.envelope, animated:true)
    }
    
    //MARK: - NSTableView Delegate/Datasource Methods
    
    // -------------------------------------------------------------------------------
    //  numberOfRowsInTableView:tableView
    // -------------------------------------------------------------------------------
    func numberOfRowsInTableView(tableView: NSTableView) -> Int {
        if self.featureSet != nil {
            return self.featureSet.features.count
        }
        return 0
    }
    
    // -------------------------------------------------------------------------------
    //  tableView:objectValueForTableColumn:tableColumn:row
    // -------------------------------------------------------------------------------
    func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
        let graphic = self.featureSet.features[row] as AGSGraphic
        return graphic.attributeAsStringForKey("STATE_NAME")
    }
    
    // -------------------------------------------------------------------------------
    //  tableViewSelectionDidChange:aNotification
    // -------------------------------------------------------------------------------
    func tableViewSelectionDidChange(notification: NSNotification) {
    
        if self.featureSet != nil && self.featureSet.features.count > 0 {
            //remove all graphics
            self.graphicsLayer.removeAllGraphics()
            
            //get selected graphic
            let graphic = self.featureSet.features[self.tableView.selectedRow] as AGSGraphic
            
            //add graphic to graphics layer and select
            self.graphicsLayer.addGraphic(graphic)
            self.graphicsLayer.setSelected(true, forGraphic:graphic)
            
            //zoom to graphic geometry
            self.mapView.zoomToGeometry(graphic.geometry, withPadding:700, animated:true)
        }
    }
    
    //MARK: - NSSplitView delegate
    
    // -------------------------------------------------------------------------------
    //  splitView:constrainMaxCoordinate
    // -------------------------------------------------------------------------------
    func splitView(splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
        return 350
    }
    
    // -------------------------------------------------------------------------------
    //  splitView:constrainMinCoordinate
    // -------------------------------------------------------------------------------
    func splitView(splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
        return 250
    }
    
    //MARK: - Search Action
    
    // -------------------------------------------------------------------------------
    //  searchAction:sender
    // -------------------------------------------------------------------------------
    @IBAction func searchAction(sender:AnyObject) {
    
        //if search field has string value
        if !self.searchField.stringValue.isEmpty {
        
            //remove all graphics
            self.graphicsLayer.removeAllGraphics()
            
            //reset featureSet and reload table
            self.featureSet = nil
            self.tableView.reloadData()
            
            //get search string and execute query
            self.query.text = self.searchField.stringValue.capitalizedString
            self.query.outSpatialReference = self.mapView.spatialReference
            self.queryTask.executeWithQuery(self.query)
        }
        else {//search field is empty
            
            //remove all graphics
            self.graphicsLayer.removeAllGraphics()
            
            //reset featureSet and reload table
            self.featureSet = nil
            self.tableView.reloadData()
            
            //zoom to predefined extent
            self.mapView.zoomToEnvelope(self.envelope, animated:true)
        }
    }
    
    //MARK: - QueryTask Delegate
    
    // -------------------------------------------------------------------------------
    //  queryTask:didExecuteWithFeatureSetResult:featureSet
    //
    //  this will be called when query task executes successfully
    // -------------------------------------------------------------------------------
    func queryTask(queryTask: AGSQueryTask!, operation op: NSOperation!, didExecuteWithFeatureSetResult featureSet: AGSFeatureSet!) {
        //get feature, and load into table
        self.featureSet = featureSet
        self.tableView.reloadData()
    }
    
    // -------------------------------------------------------------------------------
    //  queryTask:didFailWithError:error
    //
    //  this will be called when there is an error, show it to user
    // -------------------------------------------------------------------------------
    func queryTask(queryTask: AGSQueryTask!, operation op: NSOperation!, didFailWithError error: NSError!) {
        if let viewWindow = self.view.window {
            let alert = NSAlert()
            alert.messageText = "Failed to execute query"
            alert.informativeText = error.localizedDescription
            alert.beginSheetModalForWindow(viewWindow, modalDelegate:self, didEndSelector:nil, contextInfo:nil)
        }
    }
}
//OBJECTIVE C SAMPLE CODE
/*
 Copyright 2013 Esri
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#import "QueryTaskSample.h"

//layer urls
#define kBaseMapURL @"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"
#define kDynamicMapServiceURL @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer"
#define kStatesURL @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"

@interface QueryTaskSample ()

@end

@implementation QueryTaskSample

#pragma mark - awakeFromNib

// -------------------------------------------------------------------------------
//  awakeFromNib
// -------------------------------------------------------------------------------
- (void)awakeFromNib {
    
    
    //add base layer to map
	AGSTiledMapServiceLayer *baseMapLayer = [[AGSTiledMapServiceLayer alloc] initWithURL:[NSURL URLWithString:kBaseMapURL]];
    [self.mapView addMapLayer:baseMapLayer withName:@"Base Layer"];
    
    //add dynamic layer to map
    //set visible layers
    AGSDynamicMapServiceLayer *dynamicLayer = [AGSDynamicMapServiceLayer dynamicMapServiceLayerWithURL:[NSURL URLWithString:kDynamicMapServiceURL]];
    dynamicLayer.visibleLayers = @[@"5"];
    [self.mapView addMapLayer:dynamicLayer withName:@"US States"];
    
    //create simple fill symbol for graphic layer's renderer
    AGSSimpleFillSymbol *sfs = [[AGSSimpleFillSymbol alloc] init];
	sfs.color = [[NSColor greenColor] colorWithAlphaComponent:0.5];
    sfs.outline.color = [NSColor colorWithRed:0 green:128 blue:0 alpha:1.0];
    sfs.outline.width = 4;
    
    //add graphics layer to map
    //set simple renderer
    self.graphicsLayer = [AGSGraphicsLayer graphicsLayer];
    self.graphicsLayer.renderer = [AGSSimpleRenderer simpleRendererWithSymbol:sfs];
    [self.mapView addMapLayer:self.graphicsLayer withName:@"Graphics Layer"];
           
    //setup query task against layer, specify the delegate
	self.queryTask = [AGSQueryTask queryTaskWithURL:[NSURL URLWithString:kStatesURL]];
	self.queryTask.delegate = self;
	
	//setup query
	self.query = [AGSQuery query];
	self.query.outFields = [NSArray arrayWithObjects:@"*", nil];
    self.query.returnGeometry = TRUE;
    
    //zoom to predefined extend with known spatial reference of the map
    self.envelope = [AGSEnvelope envelopeWithXmin: -19749568.092138 ymin:2466036.346731 xmax:-6534031.777518 ymax:11595745.868985 spatialReference:[AGSSpatialReference webMercatorSpatialReference]];
    [self.mapView zoomToEnvelope:self.envelope animated:YES];
}

#pragma mark - NSTableView Delegate/Datasource Methods

// -------------------------------------------------------------------------------
//  numberOfRowsInTableView:tableView
// -------------------------------------------------------------------------------
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [self.featureSet.features count];
}

// -------------------------------------------------------------------------------
//  tableView:objectValueForTableColumn:tableColumn:row
// -------------------------------------------------------------------------------
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    AGSGraphic *graphic = [self.featureSet.features objectAtIndex:row];
    return [graphic attributeAsStringForKey:@"STATE_NAME"];
}

// -------------------------------------------------------------------------------
//  tableViewSelectionDidChange:aNotification
// -------------------------------------------------------------------------------
- (void)tableViewSelectionDidChange: (NSNotification *)aNotification {
    
    if ([self.featureSet.features count] > 0) {
        //remove all graphics
        [self.graphicsLayer removeAllGraphics];
        
        //get selected graphic
        AGSGraphic *graphic = [self.featureSet.features objectAtIndex:[self.tableView selectedRow]];
        
        //add graphic to graphics layer and select
        [self.graphicsLayer addGraphic:graphic];
        [self.graphicsLayer setSelected:YES forGraphic:graphic];
        
        //zoom to graphic geometry
        [self.mapView zoomToGeometry:graphic.geometry withPadding:700 animated:YES];
    }    
}

#pragma mark - NSSplitView delegate

// -------------------------------------------------------------------------------
//  splitView:constrainMaxCoordinate
// -------------------------------------------------------------------------------
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex {
    return 350;
}

// -------------------------------------------------------------------------------
//  splitView:constrainMinCoordinate
// -------------------------------------------------------------------------------
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex {
    return 250;
}

#pragma mark - Search Action

// -------------------------------------------------------------------------------
//  searchAction:sender
// -------------------------------------------------------------------------------
- (IBAction)searchAction:(id)sender {
    
    //if search field has string value
    if (self.searchField.stringValue && [self.searchField.stringValue isNotEqualTo:@""]) {
               
        //remove all graphics
        [self.graphicsLayer removeAllGraphics];
        
        //reset featureSet and reload table
        self.featureSet = nil;
        [self.tableView reloadData];
        
        //get search string and execute query
        self.query.text = [self.searchField.stringValue capitalizedString];
        self.query.outSpatialReference = self.mapView.spatialReference;
        [self.queryTask executeWithQuery:self.query];
    }
    else {//search field is empty
        
        //remove all graphics
        [self.graphicsLayer removeAllGraphics];
               
        //reset featureSet and reload table
        self.featureSet = nil;
        [self.tableView reloadData];
        
        //zoom to predefined extent
        [self.mapView zoomToEnvelope:self.envelope animated:YES];
    }
}

#pragma mark - QueryTask Delegate

// -------------------------------------------------------------------------------
//  queryTask:didExecuteWithFeatureSetResult:featureSet
//
//  this will be called when query task executes successfully
// -------------------------------------------------------------------------------
- (void)queryTask:(AGSQueryTask *)queryTask operation:(NSOperation *)op didExecuteWithFeatureSetResult:(AGSFeatureSet *)featureSet {
	//get feature, and load into table
	self.featureSet = featureSet;
	[self.tableView reloadData];
}

// -------------------------------------------------------------------------------
//  queryTask:didFailWithError:error
//
//  this will be called when there is an error, show it to user
// -------------------------------------------------------------------------------
- (void)queryTask:(AGSQueryTask *)queryTask operation:(NSOperation *)op didFailWithError:(NSError *)error {

    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"Failed to exectue query"];
    [alert setInformativeText:[NSString stringWithFormat:@"%@",error]];
    [alert beginSheetModalForWindow:self.view.window modalDelegate:self didEndSelector:nil contextInfo:nil];
}

@end
//OBJECTIVE C SAMPLE CODE
/*
 Copyright 2013 Esri
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#import <Cocoa/Cocoa.h>

@interface QueryTaskSample : NSViewController <AGSQueryTaskDelegate>

@property (strong) IBOutlet AGSMapView *mapView;
@property (strong) IBOutlet NSSearchField *searchField;
@property (strong) IBOutlet NSTableView *tableView;
@property (strong) AGSGraphicsLayer *graphicsLayer;
@property (strong) AGSQueryTask *queryTask;
@property (strong) AGSQuery *query;
@property (strong) AGSFeatureSet *featureSet;
@property (strong) AGSEnvelope *envelope;

- (IBAction)searchAction:(id)sender;

@end
Feedback on this topic?