How to geocode a table of addresses


In this topic


Using the geoprocessing tool

Use the GeocodeAddresses geoprocessing tool when the geocoding properties or additional output fields do not need updating. For more complex workflows and flexibility, see Using ArcObjects in this topic.
See the following parameter descriptions:
  • in_table parameter—Reference to the address table that gets geocoded. 
  • address_locator parameter—Reference to the address locator used to geocode the table of addresses. 
  • in_address_fields parameter—String that maps the locator field name to the address table field name. 
  • out_feature_class—Contains the geocoded features. 
  • out_relationship_type—Specifies if the relationship between the address table and geocoded feature class is a static geocoded feature class or a dynamically updated feature class.
See the following code example:
[C#]
public void GeocodeAddressesTool()
{
    Geoprocessor GP = new Geoprocessor();
    GeocodeAddresses geocodeAddresses = new GeocodeAddresses();
    geocodeAddresses.in_table = "C:\\UnitedStates.gdb\\addresses";
    geocodeAddresses.address_locator = "C:\\UnitedStates.gdb\\US_Locator";
    geocodeAddresses.in_address_fields = "Street Address VISIBLE NONE;" + 
        "City City VISIBLE NONE;" + "State State VISIBLE NONE;" + 
        "ZIP ZIP VISIBLE NONE";
    geocodeAddresses.out_feature_class = 
        "C:\\UnitedStates.gdb\\US_Addresses_Geocoded";
    geocodeAddresses.out_relationship_type = "STATIC";
    try
    {
        IGeoProcessorResult result = GP.Execute(geocodeAddresses, null)as
            IGeoProcessorResult;
        if (result != null)
        {
            if (result.Status != esriJobStatus.esriJobSucceeded)
                Console.WriteLine("Failed to geocode the address table: ");
            else
                Console.WriteLine("Geocoded the address table successfully. ");
        }
        else
        {
            if (GP.MessageCount != 0)
            {
                for (int i = 0; i < GP.MessageCount; i++)
                {
                    Console.WriteLine("GP Message " + i + " " + GP.GetMessage(i));
                }
            }
            else
                Console.WriteLine("Execution failed with no status. ");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(
            "An Exception occured while executing the GeocodeAddresses Tool:  " + e);
    }
}
[VB.NET]
Public Sub GeocodeAddressesTool_Test()
    Dim GP As ESRI.ArcGIS.Geoprocessor.Geoprocessor = New ESRI.ArcGIS.Geoprocessor.Geoprocessor
    Dim geocodeAddresses As GeocodeAddresses = New GeocodeAddresses()
    geocodeAddresses.in_table = "C:\UnitedStates.gdb\addresses"
    geocodeAddresses.address_locator = "C:\UnitedStates.gdb\US_Locator"
    geocodeAddresses.in_address_fields = "Street Address VISIBLE NONE;" & "City City VISIBLE NONE;" & "State State VISIBLE NONE;" & "ZIP ZIP VISIBLE NONE"
    geocodeAddresses.out_feature_class = "C:\UnitedStates.gdb\US_Addresses_Geocoded"
    geocodeAddresses.out_relationship_type = "STATIC"
    Try
    Dim result As IGeoProcessorResult = GP.Execute(geocodeAddresses, Nothing)
    If (Not result Is Nothing) Then
        If (Not result.Status = esriJobStatus.esriJobSucceeded) Then
            Console.WriteLine("Failed to geocode the address table: ")
        Else
            Console.WriteLine("Geocoded the address table successfully. ")
        End If
    Else
        If (Not GP.MessageCount = 0) Then
            For i As Integer = 0 To GP.MessageCount - 1
                Console.WriteLine("GP Message " & i & " " + GP.GetMessage(i))
            Next
        Else
            Console.WriteLine("Execution failed with no status. ")
        End If
    End If
    Catch ex As Exception
    Console.WriteLine("An Exception occured while executing the GeocodeAddresses Tool:  " & ex.ToString())
    End Try
End Sub

Using ArcObjects

Use the MatchTable method to geocode a table of addresses. The AddressTable parameter is a reference to the table object that contains the addresses to geocode. The addressFieldNames parameter is a comma-delimited string containing the field names in the address table that contains the address information. See the following:
  1. Specify the field names in this string in the same order as the Field objects in the Field collections returned by the AddressFields property on the IAddressInputs interface.
  2. When geocoding a table of addresses, create the feature class that contains the geocoded features and pass it to the MatchTable method using the outputFeatureClass parameter. At a minimum, the geocoded feature class must contain an ObjectID field and the match fields defined by the MatchFields property, as well as a copy of all fields from the address table that contains the address information.
  3. The outputFieldNames parameter is a comma-delimited string that contains the match field names in the geocoded feature class. Specify the field names in this string in the same order as the Field objects in the Field collections returned by the MatchFields property. The fieldsToCopy parameter is a PropertySet defining the fields from the address table to copy to the output feature class. The property names are the field names in the output feature class, and the property names are the corresponding field names in the address table.
  4. When you use the MatchTable method to geocode a table of addresses, use the AttachLocator method on ILocatorAttach2 on the LocatorWorkspace to attach a copy of the locator to the geocoded feature class. The geocoded feature class can be rematched when a copy of the locator is attached.

    See the following code example:
[VB.NET]
Sub AddressGeocodingMatchTable()
    ' Open an File Geodatabase
    Dim obj As System.Object = Activator.CreateInstance(Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"))
    Dim workspaceFactory As IWorkspaceFactory = obj
    Dim workspace As IWorkspace = workspaceFactory.OpenFromFile("C:\UnitedStates.gdb", 0)
    
    ' Open the Locator Workspace
    obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager"))
    Dim locatorManager As ILocatorManager = obj
    Dim locatorWorkspace As ILocatorWorkspace = locatorManager.GetLocatorWorkspace(workspace)
    
    ' Get a Locator
    Dim locator As ILocator = locatorWorkspace.GetLocator("USLocator")
    Dim addressGeocoding As IAddressGeocoding = locator
    
    ' Open the Table to geocode
    Dim featureWorkspace As IFeatureWorkspace = workspace
    Dim addressTable As ITable = featureWorkspace.OpenTable("addresses")
    
    ' Create a Feature Class to contain the geocoding results
    ' The Feature Class must contain an ObjectID Field, all of the MatchFields returned by the Locator,
    '  and Fields that contain the address input values
    Dim fieldsEdit As IFieldsEdit = New Fields
    Dim fieldEdit As IFieldEdit = New Field
    fieldEdit.Name_2 = "OBJECTID"
    fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID
    fieldsEdit.AddField(fieldEdit)
    
    ' Add the match fields that were returned by the locator to the fieldsEdit object
    ' This object will be added to a new Feature Class that will be created later
    Dim matchFields As IFields = addressGeocoding.MatchFields
    Dim fieldCount As Integer = matchFields.FieldCount
    Dim outputFieldNames As String = ""
    For i As Integer = 0 To fieldCount - 1
        fieldsEdit.AddField(matchFields.Field(i))
        
        ' Create a comma delimited string of the output fields for MatchTable and AttachLocator
        If (outputFieldNames.Length <> 0) Then
            outputFieldNames = outputFieldNames + ","
        End If
        outputFieldNames = outputFieldNames + matchFields.Field(i).Name
    Next
    
    ' Add fields that will be copied over during geocoding
    ' In this case, we are copying all of the fields from the address table except the OID field
    Dim addressTableFields As IFields = addressTable.Fields
    Dim fieldsToCopy As IPropertySet = New PropertySet
    fieldCount = addressTableFields.FieldCount
    Dim fieldName As String = ""
    For i As Integer = 0 To fieldCount - 1
        Dim field As IField = addressTableFields.Field(i)
        If field.Type <> esriFieldType.esriFieldTypeOID Then
            fieldsEdit.AddField(field)
            fieldsToCopy.SetProperty(field.Name, field.Name)
        End If
    Next
    
    Dim uidField As New UID
    uidField.Value = "esriGeodatabase.Feature"
    
    ' Create the new feature class that will contain all of the geocoded addresses
    Dim featureClass As IFeatureClass = featureWorkspace.CreateFeatureClass("Locations", fieldsEdit, uidField, _
                                        Nothing, esriFeatureType.esriFTSimple, "Shape", "")
    
    ' Get address Inputs
    ' This is an automated way to get the address inputs from the address table and may not always
    ' get all of the correct field names from the table.  You can also specify the address inputs
    ' manually by just creating a string but make sure you have the right amount of fields or the
    ' call to MatchTable will throw an exception.
    ' ex. String addressFieldNames = "ADDRESS,CITY,STATE,ZIP";
    Dim addressInputs As IAddressInputs = locator
    Dim addressFields As IFields = addressInputs.AddressFields
    fieldCount = addressFields.FieldCount
    fieldName = ""
    Dim addressFieldNames As String = ""
    For i As Integer = 0 To fieldCount - 1
        
        If addressFieldNames <> "" Then
            addressFieldNames + = ","
        End If
        
        ' If the address field from the locator can't be found in the table, loop through the default input
        ' field names to see if one of the other names exists in the address table.
        fieldName = addressFields.Field(i).Name
        Dim defaultInputFieldNames() As String = addressInputs.DefaultInputFieldNames(fieldName)
        If addressTable.Fields.FindField(fieldName) = -1 Then ' FindField returns -1 if the field is not found
            For j As Integer = 0 To defaultInputFieldNames.Length - 1
                If addressTable.Fields.FindField(defaultInputFieldNames(j)) <> -1 Then
                    fieldName = defaultInputFieldNames(j)
                    Exit For
                End If
            Next
        End If
        addressFieldNames + = fieldName
    Next
    
    ' Geocode the Table into the Feature Class
    addressGeocoding.MatchTable(addressTable, addressFieldNames, "", featureClass, outputFieldNames, fieldsToCopy, Nothing)
    
    ' Attach the Locator to the geocoded Feature Class
    Dim locatorAttach As ILocatorAttach2 = locatorWorkspace
    Dim table_FeatureClass As ITable = featureClass
    locatorAttach.AttachLocator(locator, table_FeatureClass, addressFieldNames, outputFieldNames)
    
    'Dim ds As IDataset = featureClass
    'ds.Delete()
End Sub
[C#]
public void geocodeAddressTable()
{
    // Open the file Geodatabase
    System.Object obj = Activator.CreateInstance(Type.GetTypeFromProgID(
        "esriDataSourcesGDB.FileGDBWorkspaceFactory"));
    IWorkspaceFactory2 workspaceFactory = obj as IWorkspaceFactory2;
    IWorkspace workspace = workspaceFactory.OpenFromFile(@"C:\UnitedStates.gdb", 0);

    // Get the Locator Workspace
    obj = Activator.CreateInstance(Type.GetTypeFromProgID(
        "esriLocation.LocatorManager"));
    ILocatorManager2 locatorManager = obj as ILocatorManager2;
    ILocatorWorkspace locatorWorkspace = locatorManager.GetLocatorWorkspace
        (workspace);

    // Get the Locator for the locator Workspace
    ILocator locator = locatorWorkspace.GetLocator("USLocator");
    IAddressGeocoding addressGeocoding = locator as IAddressGeocoding;
    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
    ITable tableOfAddresses = featureWorkspace.OpenTable("Addresses");

    // Create a feature class to contain the geocoding results.
    // The feature class must contain an ObjectID field, all of the match fields returned by the locator,
    // and fields that contain the address input values.
    IFieldsEdit fieldsEdit = new FieldsClass();
    IFieldEdit fieldEdit = new FieldClass();
    fieldEdit.Name_2 = "OBJECTID";
    fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
    fieldsEdit.AddField(fieldEdit);

    // Add the match fields that were returned by the locator to the fieldsEdit object 
    // This object will be added to a new Feature Class that will be created later
    IFields matchFields = addressGeocoding.MatchFields;
    int matchFieldCount = matchFields.FieldCount;
    String outputFieldNames = "";
    for (int i = 0; i < matchFieldCount; i++)
    {
        IField field = matchFields.get_Field(i);
        fieldsEdit.AddField(field);

        //Create a comma delimited string of the output fields for MatchTable and AttachLocator
        if (outputFieldNames != "")
            outputFieldNames += ",";

        outputFieldNames += field.Name;
    }

    // Add fields that will be copied over during geocoding
    // In this case, we are copying all of the fields from the address table except the OID field
    IFields addressTableFields = tableOfAddresses.Fields;
    IPropertySet fieldsToCopy = new PropertySetClass();
    int fieldCount = addressTableFields.FieldCount;
    String fieldName = "";
    for (int i = 0; i < fieldCount; i++)
    {
        IField field = addressTableFields.get_Field(i);
        if (field.Type != esriFieldType.esriFieldTypeOID)
        {
            fieldsEdit.AddField(field);
            fieldsToCopy.SetProperty(field.Name, field.Name);
        }
    }

    UID pUID = new UIDClass();
    pUID.Value = "esriGeodatabase.Feature";

    // Create the feature class to geocode the addresses into
    IFeatureClass featureClass = featureWorkspace.CreateFeatureClass("Locations",
        fieldsEdit, pUID, null, esriFeatureType.esriFTSimple, "Shape", "");

    // Get address Inputs
    // This is an automated way to get the address inputs from the address table and may not always
    // get all of the correct field names from the table.  You can also specify the address inputs
    // manually by just creating a string but make sure you have the right amount of fields or the 
    // call to MatchTable will throw an exception.
    // ex. String addressFieldNames = "ADDRESS,CITY,STATE,ZIP";
    IAddressInputs addressInputs = locator as IAddressInputs;
    IFields addressFields = addressInputs.AddressFields;
    fieldCount = addressFields.FieldCount;
    fieldName = "";
    String addressFieldNames = "";
    for (int i = 0; i < fieldCount; i++)
    {
        if (addressFieldNames != "")
            addressFieldNames += ",";

        // If the address field from the locator can't be found in the table, loop through the default input
        // field names to see if one of the other names exists in the address table.
        fieldName = addressFields.get_Field(i).Name;
        String[] defaultInputFieldNames = addressInputs.get_DefaultInputFieldNames
            (fieldName)as String[];
        if (tableOfAddresses.Fields.FindField(fieldName) ==  - 1)
        // FindField returns -1 if the field is not found
        {
            for (int j = 0; j < defaultInputFieldNames.Length; j++)
            {
                if (tableOfAddresses.Fields.FindField(defaultInputFieldNames[j]) != 
                    - 1)
                {
                    fieldName = defaultInputFieldNames[j];
                    break;
                }
            }
        }
        addressFieldNames += fieldName;
    }

    // Geocode the table into the feature class.
    addressGeocoding.MatchTable(tableOfAddresses, addressFieldNames, "",
        featureClass, outputFieldNames, fieldsToCopy, null);

    // Attach the locator to the geocoded feature class.
    ILocatorAttach2 locatorAttach2 = locatorWorkspace as ILocatorAttach2;
    ITable table_FeatureClass = featureClass as ITable;
    locatorAttach2.AttachLocator(locator, table_FeatureClass, addressFieldNames,
        outputFieldNames);

    //IDataset ds = featureClass as IDataset;
    //ds.Delete();
}

Using IGeocodeServer

Use the GeocodeAddresses method to geocode a table of addresses with ArcGIS Server. The AddressTable parameter is a reference to the RecordSet that contains the addresses to geocode. The addressFieldMapping parameter defines the mapping of address fields used by the GeocodeServer to fields in the AddressTable RecordSet. See the following:
  1. Get the field names returned by the GetAddressFields method and set them as the name of the PropertySet for the addressFieldMapping. The values of the properties are the names of the corresponding fields in the RecordSet.

    See the following code example:
[VB.NET]
Public Sub GeocodeAddressesWithServer()
    
    ' Open a GISServerConnection.
    Dim gisServerConnection As IGISServerConnection = New GISServerConnectionClass
    gisServerConnection.Connect("mendota")
    
    ' Get a GeocodeServer from the GISServerConnection.
    Dim serverObjectManager As IServerObjectManager = gisServerConnection.ServerObjectManager
    Dim serverContext As IServerContext = serverObjectManager.CreateServerContext("USA Streets", "GeocodeServer")
    Dim serverObject_GeocodeServer As IServerObject = serverContext.ServerObject
    Dim geocodeServer As IGeocodeServer = CType(serverObject_GeocodeServer, IGeocodeServer)
    
    ' Set up the Feature Workspace and get the address table
    obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"))
    Dim workspaceFactory As IWorkspaceFactory2 = obj
    Dim workspace As IWorkspace = workspaceFactory.OpenFromFile("C:\UnitedStates.gdb", 0)
    Dim featureWorkspace As IFeatureWorkspace = workspace
    Dim addressTable As ITable = featureWorkspace.OpenTable("addresses")
    
    ' Create a recordSet from the address table to be used to geocode against the server
    Dim fields As IFields = geocodeServer.GetAddressFields()
    Dim recordSetInit As IRecordSetInit = New RecordSet
    recordSetInit.SetSourceTable(addressTable, Nothing)
    
    ' The PropertySet consists of key = "locator field name", value = "corresponding field from recordSet"
    Dim addressFieldMapping As IPropertySet = New PropertySet
    addressFieldMapping.SetProperty(fields.Field(0).Name, "ADDRESS")
    addressFieldMapping.SetProperty(fields.Field(1).Name, "CITY")
    addressFieldMapping.SetProperty(fields.Field(2).Name, "STATE")
    addressFieldMapping.SetProperty(fields.Field(3).Name, "ZIP")
    
    Dim geocodingResults As IRecordSet = geocodeServer.GeocodeAddresses(recordSetInit, addressFieldMapping, Nothing)
    
    ' Print out the results
    Dim cursor As ICursor = geocodingResults.Cursor(True)
    Dim result As IRow = cursor.NextRow()
    Dim Count As Integer = 1
    Dim Size As Integer = result.Fields.FieldCount
    Dim point As IPoint
    While Not result Is Nothing
        Console.WriteLine("Row " + Count.ToString())
        
        For i As Integer = 0 To Size - 1
            If (result.Fields.Field(i).Name = "Shape") Then
                point = result.Value(i)
                If (Not point.IsEmpty) Then
                    Console.WriteLine(result.Fields.Field(i).Name + " = " + point.X.ToString() + ", " + point.Y.ToString())
                End If
            Else
                Console.WriteLine(result.Fields.Field(i).Name + " = " + result.Value(i).ToString())
            End If
        Next
        result = cursor.NextRow()
        Count = Count + 1
        Console.WriteLine()
    End While
    
End Sub
[C#]
public void GeocodeSingleAddressOnGeocodeServer()
{

    // Open a GISServerConnection.
    IGISServerConnection gisServerConnection = new GISServerConnectionClass();
    gisServerConnection.Connect("mendota");

    // Get a GeocodeServer from the GISServerConnection.
    IServerObjectManager serverObjectManager =
        gisServerConnection.ServerObjectManager;
    IServerContext serverContext = serverObjectManager.CreateServerContext(
        "USA Streets", "GeocodeServer");
    IServerObject serverObject_GeocodeServer = serverContext.ServerObject;
    IGeocodeServer geocodeServer = (IGeocodeServer)serverObject_GeocodeServer;

    // Set up the Feature Workspace and get the address table
    obj = Activator.CreateInstance(Type.GetTypeFromProgID(
        "esriDataSourcesGDB.FileGDBWorkspaceFactory"));
    IWorkspaceFactory workspaceFactory = obj as IWorkspaceFactory;
    IWorkspace workspace = workspaceFactory.OpenFromFile(@"C:\UnitedStates.gdb", 0);
    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
    ITable addressTable = featureWorkspace.OpenTable("Addresses");

    // Create a recordSet from the address table to be used to geocode against the server
    IFields fields = geocodeServer.GetAddressFields();
    IRecordSetInit recordSetInit = new RecordSetClass();
    recordSetInit.SetSourceTable(addressTable, null);

    // The PropertySet consists of key = "locator field name", value = "corresponding field from recordSet"
    IPropertySet addressFieldMapping = new PropertySetClass();
    addressFieldMapping.SetProperty(fields.get_Field(0).Name, "ADDRESS");
    addressFieldMapping.SetProperty(fields.get_Field(1).Name, "CITY");
    addressFieldMapping.SetProperty(fields.get_Field(2).Name, "STATE");
    addressFieldMapping.SetProperty(fields.get_Field(3).Name, "ZIP");

    IRecordSet geocodingResults = geocodeServer.GeocodeAddresses(recordSetInit as
        IRecordSet, addressFieldMapping, null);

    // Print out the results
    ICursor cursor = geocodingResults.get_Cursor(true);
    IRow result = cursor.NextRow();
    int count = 1;
    while (result != null)
    {
        Console.WriteLine("ROW " + count);
        int size = result.Fields.FieldCount;
        for (int i = 0; i < size; i++)
        {
            if (result.Fields.get_Field(i).Name == "Shape")
            {
                IPoint addressPoint = result.get_Value(i)as IPoint;
                if (!addressPoint.IsEmpty)
                    Console.WriteLine(result.Fields.get_Field(i).Name + " = " +
                        addressPoint.X + ", " + addressPoint.Y);
            }
            else
                Console.WriteLine(result.Fields.get_Field(i).Name + " = " +
                    result.get_Value(i));
        }
        result = cursor.NextRow();
        count++;
        Console.WriteLine();
    }
}


See Also:

Location library overview
How to geocode a single address




To use the code in this topic, reference the following assemblies in your Visual Studio project. In the code files, you will need using (C#) or Imports (VB .NET) directives for the corresponding namespaces (given in parenthesis below if different from the assembly name):
Development licensing Deployment licensing
Engine Developer Kit Engine Runtime
ArcView ArcView
ArcEditor ArcEditor
ArcInfo ArcInfo