Geocoding

Download Sample Application

Locate an address or a place on the map using this sample. Simply specify an address or place in the search control in the upper right of the application and press enter. The resulting match candidates are then displayed as pushpins on the map. Click on these to view the address in the callout.

@property (strong) AGSLocator *locator;

//init arcgis locator and set delegate
self.locator = [AGSLocator locator];
self.locator.delegate = self;

//setup find parameters
AGSLocatorFindParameters *findParams = [[AGSLocatorFindParameters alloc] init];
findParams.outFields = @[@"*"];
findParams.outSpatialReference = self.mapView.spatialReference;
findParams.text = @"the address";
        
//execute find
[self.locator findWithParameters:findParams];

//process results
- (void)locator:(AGSLocator *)locator operation:(NSOperation *)op didFind:(NSArray *)results {
    ...
}

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 url
let kGBaseMapURL = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"

class GeocodingSwiftSample: NSViewController, AGSMapViewTouchDelegate, AGSLocatorDelegate {

    @IBOutlet weak var mapView:AGSMapView!
    @IBOutlet weak var searchField:NSSearchField!
    
    var locator:AGSLocator!
    var graphicsLayer:AGSGraphicsLayer!
    var calloutTemplate:AGSCalloutTemplate!

    //MARK: - awakeFromNib
    
    // -------------------------------------------------------------------------------
    //  awakeFromNib
    // -------------------------------------------------------------------------------
    override func awakeFromNib() {
        
        //add base layer
        let baseMapLayer = AGSTiledMapServiceLayer(URL: NSURL(string: kGBaseMapURL))
        self.mapView.addMapLayer(baseMapLayer, withName:"Base Layer")
        self.mapView.enableWrapAround()
        
        //create picture marker symbol
        let pms = AGSPictureMarkerSymbol(imageNamed: "bluepin")
        pms.leaderPoint = CGPoint(x: 4,y: 17)
        
        //add graphics layer using the picture marker symbol above
        self.graphicsLayer = AGSGraphicsLayer()
        self.graphicsLayer.renderer = AGSSimpleRenderer(symbol: pms)
        //setup callout template
        self.calloutTemplate = AGSCalloutTemplate()
        self.calloutTemplate.titleTemplate = "${Match_addr}"
        self.calloutTemplate.detailTemplate = "${Region}"
        
        //set layer callout delegate
        self.graphicsLayer.calloutDelegate = self.calloutTemplate
        
        self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer")
        
        //init arcgis locator and set delegate
        self.locator = AGSLocator()
        self.locator.delegate = self
    }
    
    //MARK: - Actions
    
    // -------------------------------------------------------------------------------
    //  searchAction:sender
    // -------------------------------------------------------------------------------
    @IBAction func searchAction(sender:AnyObject) {
    
        //determine if there is text in the search field, if so, find the locations for the address
        if !self.searchField.stringValue.isEmpty {
        
            //setup find parameters
            let findParams = AGSLocatorFindParameters()
            findParams.outFields = ["*"]
            findParams.outSpatialReference = self.mapView.spatialReference
            findParams.text = self.searchField.stringValue
            
            //execute find
            self.locator.findWithParameters(findParams)
        }
        else {//search field is empty
            
            //hide callout
            self.mapView.callout.hidden = true
            
            //remove all graphics
            self.graphicsLayer.removeAllGraphics()
        }
    }
    
    //MARK: - Locator Delegate

    // -------------------------------------------------------------------------------
    //  locator:didFind
    //
    //  this will be called when locator find results successfully
    // -------------------------------------------------------------------------------
    func locator(locator: AGSLocator!, operation op: NSOperation!, didFind results: [AnyObject]!) {
        //hide callout
        self.mapView.callout.hidden = true
        
        //remove all graphics from graphics layer
        self.graphicsLayer.removeAllGraphics()
        
        if results.count == 0 {
            if let viewWindow = self.view.window {
                let alert = NSAlert()
                alert.messageText = "No Results"
                alert.informativeText = "No results found by locator"
                alert.beginSheetModalForWindow(viewWindow, modalDelegate:self, didEndSelector:nil, contextInfo:nil)
            }
        }
        else {
            //graphics array to hold result graphics
            var graphics = Array<AGSGraphic>()
            
            for findResult in results as [AGSLocatorFindResult] {
                let graphic = findResult.graphic
                graphics.append(graphic)
            }
            
            //add graphics to graphics layer
            self.graphicsLayer.addGraphics(graphics)
            
            //zoom to graphics layer
            self.mapView.zoomToGeometry(self.graphicsLayer.fullEnvelope, withPadding:100, animated:true)
        }
    }
    
    // -------------------------------------------------------------------------------
    //  locator:didFailToFindWithError
    //
    //  this will be called when locator fails with error, show it to user
    // -------------------------------------------------------------------------------
    func locator(locator: AGSLocator!, operation op: NSOperation!, didFailToFindWithError error: NSError!) {
        //show error
        if let viewWindow = self.view.window {
            let alert = NSAlert()
            alert.messageText = "Failed to find address/POI"
            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 "GeocodingSample.h"

//layer url
#define kBaseMapURL @"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"

@interface GeocodingSample ()

@end

@implementation GeocodingSample

#pragma mark - awakeFromNib

// -------------------------------------------------------------------------------
//  awakeFromNib
// -------------------------------------------------------------------------------
- (void)awakeFromNib {
    
    //add base layer
	AGSTiledMapServiceLayer *baseMapLayer = [[AGSTiledMapServiceLayer alloc] initWithURL:[NSURL URLWithString:kBaseMapURL]];
    [self.mapView addMapLayer:baseMapLayer withName:@"Base Layer"];
    [self.mapView enableWrapAround];
    
    //create picture marker symbol
    AGSPictureMarkerSymbol *pms = [AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:@"bluepin"];
    pms.leaderPoint = CGPointMake(4,17);
    
    //add graphics layer
    self.graphicsLayer = [AGSGraphicsLayer graphicsLayer];
    self.graphicsLayer.renderer = [AGSSimpleRenderer simpleRendererWithSymbol:pms];
    //setup callout template
    self.calloutTemplate = [[AGSCalloutTemplate alloc] init];
    self.calloutTemplate.titleTemplate = @"${Match_addr}";
    self.calloutTemplate.detailTemplate = @"${Region}";
    //set layer callout delegate
    self.graphicsLayer.calloutDelegate = self.calloutTemplate;
    
    [self.mapView addMapLayer:self.graphicsLayer withName:@"Graphics Layer"];
    
    //init arcgis locator and set delegate
    self.locator = [AGSLocator locator];
    self.locator.delegate = self;
}

#pragma mark - Actions

// -------------------------------------------------------------------------------
//  searchAction:sender
// -------------------------------------------------------------------------------
- (IBAction)searchAction:(id)sender {
    
    //if search field has string value
    if (self.searchField.stringValue && [self.searchField.stringValue isNotEqualTo:@""]) {
        
        //setup find parameters
        AGSLocatorFindParameters *findParams = [[AGSLocatorFindParameters alloc] init];
        findParams.outFields = @[@"*"];
        findParams.outSpatialReference = self.mapView.spatialReference;
        findParams.text = self.searchField.stringValue;
        
        //execute find
        [self.locator findWithParameters:findParams];
    }
    else {//search field is empty
        
        //hide callout
        [self.mapView.callout setHidden:YES];
        
        //remove all graphics
        [self.graphicsLayer removeAllGraphics];
    }
}

#pragma mark - Locator Delegate

// -------------------------------------------------------------------------------
//  locator:didFind
//
//  this will be called when locator find results successfully
// -------------------------------------------------------------------------------
- (void)locator:(AGSLocator *)locator operation:(NSOperation *)op didFind:(NSArray *)results {
    
    //hide callout
    [self.mapView.callout setHidden:YES];
    
    //remove all graphics from graphics layer
    [self.graphicsLayer removeAllGraphics];
    
    if ([results count] == 0) {
        
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"No Results"];
        [alert setInformativeText:@"No results found by locator"];
        [alert beginSheetModalForWindow:self.view.window modalDelegate:self didEndSelector:nil contextInfo:nil];
    }
    else {
        
        //graphics array to hold result graphics
        NSMutableArray *graphics = [NSMutableArray array];
        
        for (AGSLocatorFindResult *findResult in results) {
            AGSGraphic *graphic = findResult.graphic;
            [graphics addObject:graphic];
        }
        
        //add graphics to graphics layer
        [self.graphicsLayer addGraphics:graphics];
        
        //zoom to graphics layer
        [self.mapView zoomToGeometry:self.graphicsLayer.fullEnvelope withPadding:100 animated:YES];
    }
}

// -------------------------------------------------------------------------------
//  locator:didFailToFindWithError
//
//  this will be called when locator fails with error, show it to user
// -------------------------------------------------------------------------------
- (void)locator:(AGSLocator *)locator operation:(NSOperation *)op didFailToFindWithError:(NSError *)error {
    //show error
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"Failed to find address/POI"];
    [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 GeocodingSample : NSViewController <AGSLocatorDelegate>

@property (strong) IBOutlet AGSMapView *mapView;
@property (strong) IBOutlet NSSearchField *searchField;
@property (strong) AGSLocator *locator;
@property (strong) AGSGraphicsLayer *graphicsLayer;
@property (strong) AGSCalloutTemplate *calloutTemplate;

- (IBAction)searchAction:(id)sender;

@end
Feedback on this topic?