Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stdavis/6601003 to your computer and use it in GitHub Desktop.
Save stdavis/6601003 to your computer and use it in GitHub Desktop.
# Utah Street Address Locator (Geocoding) Service
# AGRC, 20130329
# WHAT?
# Geocodes an input table in one of the arcgis-compatible file formats and produces
# an new output .csv table with the geocoded results
# IMPORTANT NOTES:
#
# individualized api key will be required in near future, here's how to get one:
# 1) register at http://developer.mapserv.utah.gov/AccountAccess
# 2) confirm the email address that you register with
# 3) generate an api key for your web application or desktop machine
# NOTE: arcpy is used so that the inAddressTable argument can be used with any ArcMap readable table.
# While this requires an ArcGIS Desktop license, the code could easily be written to remove the
# arcpy dependency.
import json
import arcpy
import urllib2
import os
import csv
from time import strftime
#### SET THESE 6 PARAMETERS
#1
apiKey= "" #obtain a mapserv UserName by registering at http://mapserv.utah.gov/registration/Register
#2
inAddressTable= r"c:/temp/myAddressTableToGeocode.csv"
#3
inAddressFieldName = "AddressFieldName"
#field containing basic street address exs. 120 N 200 W, 99 S Main St
#4
inZoneFieldName = "ZipFieldName" #field containing zipcode, standardized city name, or udot route number exs. 84105, Heber City
#5
inUniqueIdentifierFieldName = "" #this is default mode, will auto-number results, otherwise specify the name of objid fieldname
#6
outFileFolder = r"c:/temp/"
#### END SET PARAMETERS
rows = arcpy.SearchCursor(inAddressTable)
csvWriter = csv.writer(open(os.path.join(outFileFolder, "mapservGeocodeResults_" + strftime("%Y%m%d%H%M%S") + ".csv"), 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
csvWriter.writerow(['OBJID','INADDR','INZONE','MatchAddr','MatchZone','Geocoder','Score','X','Y'])
x = 0
for row in rows:
x += 1
if inUniqueIdentifierFieldName == "":
objID = str(x)
else:
objID = str(row.getValue(inUniqueIdentifierFieldName)).strip()
streetAddress = str(row.getValue(inAddressFieldName)).strip().replace("#","")
#remove unnecessary character
for c in range(34,48):
streetAddress = streetAddress.replace(chr(c)," ")
streetAddress = streetAddress.replace("_"," ")
zone = str(row.getValue(inZoneFieldName))
if zone[:1] == "8":
zone = zone.strip()[:5]
if len(objID) == 0 and len(streetAddress) == 0 and len(zone) == 0:
print "incomplete record detected"
continue
print objID
streetAddressForURL = urllib2.quote(streetAddress)
zoneForURL = urllib2.quote(zone)
gcServiceURL = r'http://api.mapserv.utah.gov/api/v1/Geocode/{0}/{1}?apiKey={2}'.format(streetAddressForURL,zoneForURL, apiKey)
try:
response = urllib2.urlopen(gcServiceURL)
except urllib2.HTTPError:
# No record will be written for this record of inAddressTable
print "No address found"
emptyStr =""
csvWriter.writerow([objID,streetAddress,zone,emptyStr,emptyStr,emptyStr,emptyStr,emptyStr,emptyStr])
continue
jsonGCResults = json.load(response)["result"]
splitMatchAddress = jsonGCResults["matchAddress"].split(",")
matchAddressStreet = ""
matchAddressZone = ""
if len(splitMatchAddress) == 2:
matchAddressStreet = splitMatchAddress[0]
matchAddressZone = splitMatchAddress[1]
csvWriter.writerow([objID,streetAddress,zone,matchAddressStreet,matchAddressZone,jsonGCResults["locator"],jsonGCResults["score"],jsonGCResults["location"]["x"],jsonGCResults["location"]["y"]])
del csvWriter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment