Graphics Layer

Download Sample Application

Graphics layers typically display short-term or ephemeral information such as the results of a query, user drawn information or the track of a GPS. This sample demonstrates adding graphics to the map from the results of a query. California’s counties are selected from a Dynamic Map Service Layer, the results iterated and the feature’s graphic added to a Graphics Layer. Click on the county to see the Counties name displayed in the Map View’s callout.

@property (strong) AGSGraphicsLayer *graphicsLayer;

//initialize and add the Graphicslayer to the map
self.graphicsLayer = [AGSGraphicsLayer graphicsLayer];
self.graphicsLayer.delegate = self;
[self.mapView addMapLayer:self.graphicsLayer withName:@"Graphics Layer"];

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 kGLBaseMapURL = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
let kDynamicMapServiceLayerURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/2"

class GraphicsLayerSwiftSample: NSViewController, AGSLayerDelegate, AGSMapViewLayerDelegate, AGSQueryTaskDelegate {
    
    @IBOutlet weak var mapView:AGSMapView!
    var graphicsLayer:AGSGraphicsLayer!
    var queryTask:AGSQueryTask!
    var calloutTemplate:AGSCalloutTemplate!
    
    //MARK: - Awake From Nib
    
    // -------------------------------------------------------------------------------
    //  awakeFromNib
    // -------------------------------------------------------------------------------
    override func awakeFromNib() {
    
        //set mapView's layer delegate so mapViewDidLoad called
        //and send execute query
        self.mapView.layerDelegate = self
        
        //add base layer to map and set delegate to know when layer loads or fails to load
        let baseMapLayer = AGSTiledMapServiceLayer(URL: NSURL(string: kGLBaseMapURL))
        baseMapLayer.delegate = self
        self.mapView.addMapLayer(baseMapLayer, withName:"Base Layer")
        
        //add graphics layer to display result returned by query task
        self.graphicsLayer = AGSGraphicsLayer()
        self.graphicsLayer.delegate = self
        //set callout template
        self.calloutTemplate = AGSCalloutTemplate()
        self.calloutTemplate.titleTemplate = "${NAME}"
        self.calloutTemplate.detailTemplate = "${STATE_NAME}"
        //set layer callout delegate
        self.graphicsLayer.calloutDelegate = self.calloutTemplate;
        self.mapView.addMapLayer(self.graphicsLayer, withName:"Counties Graphics Layer")
    }
    
    // -------------------------------------------------------------------------------
    //  mapViewDidLoad:mapView
    // -------------------------------------------------------------------------------
    func mapViewDidLoad(mapView: AGSMapView!) {
    
        //define a query
        let query = AGSQuery()
        query.whereClause = "STATE_NAME = 'California'"
        query.returnGeometry = true
        query.outFields = ["*"]
        query.outSpatialReference = self.mapView.spatialReference
        
        //init query task and execute a query
        self.queryTask = AGSQueryTask(URL: NSURL(string: kDynamicMapServiceLayerURL))
        self.queryTask.delegate = self
        self.queryTask.executeWithQuery(query)
    }
    
    //MARK: - Layer Delegate
    
    // -------------------------------------------------------------------------------
    //  layerDidLoad:layer
    // -------------------------------------------------------------------------------
    func layerDidLoad(layer: AGSLayer!) {
        println("Layer \(layer.name) loaded..")
    }
    
    // -------------------------------------------------------------------------------
    //  layer:didFailToLoadWithError:error
    // -------------------------------------------------------------------------------
    func layer(layer: AGSLayer!, didFailToLoadWithError error: NSError!) {
        //show error
        self.showError(error, withMessageText:"Layer '\(layer.name)' failed to load")
    }
    
    //MARK: - Query Task Delegate
    
    // -------------------------------------------------------------------------------
    //  queryTask:operation:didExecuteWithFeatureSetResult
    // -------------------------------------------------------------------------------
    func queryTask(queryTask: AGSQueryTask!, operation op: NSOperation!, didExecuteWithFeatureSetResult featureSet: AGSFeatureSet!) {
    
        //define symbol
        let simpleFillSymbol = AGSSimpleFillSymbol(color: NSColor.redColor(), outlineColor: NSColor.whiteColor())
        
        //init graphics array
        var graphics = Array<AGSGraphic>()
        
        //add callout template and symbol to all graphics
        for graphic in featureSet.features as [AGSGraphic] {
            graphic.symbol = simpleFillSymbol
            graphics.append(graphic)
        }
        
        //add all graphics to graphics layer
        self.graphicsLayer.addGraphics(graphics)
        
        //zoom to graphics layer
        self.mapView.zoomToGeometry(self.graphicsLayer.fullEnvelope, withPadding:50, animated:true)
    }
    
    // -------------------------------------------------------------------------------
    //  queryTask:operation:didFailWithError
    // -------------------------------------------------------------------------------
    func queryTask(queryTask: AGSQueryTask!, operation op: NSOperation!, didFailWithError error: NSError!) {
        //show error
        self.showError(error, withMessageText:"Query task failed")
    }
    
    //MARK: - Show Error
    
    // -------------------------------------------------------------------------------
    //  showError:withMessageText
    // -------------------------------------------------------------------------------
    func showError(error: NSError, withMessageText messageText:String) {
        if let viewWindow = self.view.window {
            let alert = NSAlert()
            alert.messageText = messageText
            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 "GraphicsLayerSample.h"

//layer urls
#define kBaseMapURL @"http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
#define kDynamicMapServiceLayerURL @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/2"

@interface GraphicsLayerSample ()

@end

@implementation GraphicsLayerSample

#pragma mark - Awake From Nib

// -------------------------------------------------------------------------------
//  awakeFromNib
// -------------------------------------------------------------------------------
- (void)awakeFromNib {
    
    //set mapView's layer delegate so mapViewDidLoad called
    //and send execute query
    self.mapView.layerDelegate = self;
    
    //add base layer to map and set delegate to know when layer loads or fails to load
	AGSTiledMapServiceLayer *baseMapLayer = [[AGSTiledMapServiceLayer alloc] initWithURL:[NSURL URLWithString:kBaseMapURL]];
    baseMapLayer.delegate = self;
	[self.mapView addMapLayer:baseMapLayer withName:@"Base Layer"];
    
    //add graphics layer to display result returned by query task
    self.graphicsLayer = [AGSGraphicsLayer graphicsLayer];
    self.graphicsLayer.delegate = self;
    //set callout template
    self.calloutTemplate = [[AGSCalloutTemplate alloc] init];
    self.calloutTemplate.titleTemplate = @"${NAME}";
    self.calloutTemplate.detailTemplate = @"${STATE_NAME}";
    //set layer callout delegate
    self.graphicsLayer.calloutDelegate = self.calloutTemplate;
    [self.mapView addMapLayer:self.graphicsLayer withName:@"Counties Graphics Layer"];
}

// -------------------------------------------------------------------------------
//  mapViewDidLoad:mapView
// -------------------------------------------------------------------------------
- (void)mapViewDidLoad:(AGSMapView *)mapView {
    
    //define a query
    AGSQuery *query = [AGSQuery query];
    query.whereClause = @"STATE_NAME = 'California'";
    query.returnGeometry = TRUE;
    query.outFields = @[@"*"];
    query.outSpatialReference = self.mapView.spatialReference;
    
    //init query task and execute a query
    self.queryTask = [AGSQueryTask queryTaskWithURL:[NSURL URLWithString:kDynamicMapServiceLayerURL]];
    self.queryTask.delegate = self;
    [self.queryTask executeWithQuery:query];
}

#pragma mark - Layer Delegate

// -------------------------------------------------------------------------------
//  layerDidLoad:layer
// -------------------------------------------------------------------------------
- (void)layerDidLoad:(AGSLayer *)layer {
    NSLog(@"Layer %@ loaded..",layer.name);
}

// -------------------------------------------------------------------------------
//  layer:didFailToLoadWithError:error
// -------------------------------------------------------------------------------
- (void)layer:(AGSLayer *)layer didFailToLoadWithError:(NSError *)error {    
    //show error
    [self showError:error withMessageText:[NSString stringWithFormat:@"Layer '%@' failed to load",layer.name]];
}

#pragma mark - Query Task Delegate

// -------------------------------------------------------------------------------
//  queryTask:operation:didExecuteWithFeatureSetResult
// -------------------------------------------------------------------------------
- (void)queryTask:(AGSQueryTask *)queryTask operation:(NSOperation *)op didExecuteWithFeatureSetResult:(AGSFeatureSet *)featureSet {
        
    //define symbol
    AGSSimpleFillSymbol *simpleFillSymbol = [AGSSimpleFillSymbol simpleFillSymbolWithColor:[NSColor redColor] outlineColor:[NSColor whiteColor]];
    
    //init graphics array
    NSMutableArray *graphics = [NSMutableArray array];
    
    //add callout template and symbol to all graphics
    for (AGSGraphic *graphic in featureSet.features) {
        graphic.symbol = simpleFillSymbol;
        [graphics addObject:graphic];
    }
    
    //add all graphics to graphics layer
    [self.graphicsLayer addGraphics:graphics];
    
    //zoom to graphics layer
    [self.mapView zoomToGeometry:self.graphicsLayer.fullEnvelope withPadding:50 animated:YES];
}

// -------------------------------------------------------------------------------
//  queryTask:operation:didFailWithError
// -------------------------------------------------------------------------------
- (void)queryTask:(AGSQueryTask *)queryTask operation:(NSOperation *)op didFailWithError:(NSError *)error {
    //show error
    [self showError:error withMessageText:@"Query task failed"];
}

#pragma mark - Show Error

// -------------------------------------------------------------------------------
//  showError:withMessageText
// -------------------------------------------------------------------------------
- (void)showError:(NSError*)error withMessageText:(NSString*)messageText {
    
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:messageText];
    [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 GraphicsLayerSample : NSViewController <AGSMapViewLayerDelegate,AGSLayerDelegate,AGSQueryTaskDelegate>

@property (strong) IBOutlet AGSMapView *mapView;
@property (strong) AGSGraphicsLayer *graphicsLayer;
@property (strong) AGSQueryTask *queryTask;
@property (strong) AGSCalloutTemplate *calloutTemplate;

@end
Feedback on this topic?