Skip to Main Content

Geography

Research Guide for geography resources and tools

Tutorials Introduction

These tutorials assume that you have access to ArcGIS either in our computer lab or installed on your computer so there won't be any instructions on how to install. They are written for someone with basic knowledge of ArcGIS's interface, that wants a walkthrough how this tool can be used to help them ask and answer their spatial research questions. 

For tutorials starting at a beginner level I recommend those on ESRI's website or if you have a New York Public Library card, they have several great tutorials for newcomers to ArcGIS on their Lynda.com portal.

The data I'll be using in these tutorials comes from felony drug arrest statistics by county that I got from the New York State Division of Criminal Justice Services, spatial data from the New York State GIS Portal and data from the Law Enforcement Support office at the Defense Logistics Agency concerning the 1033 program. In brief, the 1033 program lets local law enforcement agencies request decommissioned military equipment ranging from office furniture, to night-vision, to weapons to Mine-Resistant Ambush Proof Vehicles (MRAPs). 

While the data I'm using is real from a project that I did, it isn't going to be updated so please go back to the original sources mentioned if you'd like to explore it further. I picked these data sets because they were handy and they are large and complex enough to show how to work with different kinds of data but not too complicated to get in the way of explaining the process. The maps made in these examples are not necessarily scholarly rigorous but hopefully the process of making them will get you familiar enough with ArcGIS Pro so that when you map your own data, you'll have more time for scholarly rigor!

Learning Goals

Sometimes you'll be dealing with more granular data. Instead of a whole city, you want to map a particular address within that city, instead of a whole national park, the peak of a mountain within that park. This is point data. This can be in a shapefile of its own, in which case you'd just drag it on the canvas the same as any other shapefile. It can arrive in table form as well, as a list of addresses or as latitude and longitude coordinates, either as secondary data, or primary data you've recorded yourself with a GPS tracker.

In this exercise, you'll learn how to take a csv file with latitude and longitude coordinates, and use the Display X,Y function to add them to the map. You'll see how to use Google Maps to find the latitude and longitude for an address to revise any coordinates you may have gotten wrong and where those coordinates will be visible when your web-browser is showing information for that location.

The files below are what will be used for this exercise.  One is a list of police stations' latitudes and longitudes, geocoded-police-stations.csv that I got using Google's geocoding API and a python script. The last tab in this box is a tutorial describing how I did that, but that's out of the scope of this exercise. The other is the base map created in an earlier exercise, New York State Base Map.mxd 

Data

Getting Started

  • Download the two files above and either place in a folder that you have already connected to in the Catalog window in ArcMap or somewhere that will be easy for you to find it when you make a connection to that folder.
  • To make a connection in ArcMap, go to Folder Connections in the Catalog window, right-click, and select Connect to Folder. Navigate to the folder you have placed these files in and click OK
  • Drag the NewYorkStateBaseMap.mxd onto the canvas and it will display a map of New York State's counties, cities and villages, and place the layers on this map in the Table of Contents window.
  • Drag geocoded-police-stations.csv onto the canvas. Your map won't change since it is a table and not a shapefile, but the view in your Table of Contents window will change to the List By Source view and you'll see the file and its path displayed. 
  • Right-click on geocoded-police-stations.csv and select Open Table. Scroll through it to see the data. There are 3 columns. LEA (short for Law Enforcement Agency), Latitude and Longitude. Not a lot of information, but enough to put the items you are listing onto the map. ArcGIS can be asked to take these Latitude and Longitude numbers and turn them into points on your map.  

Locating the Geographic Coordinate System to Use for your Data

A geographic coordinate system tells ArcMap how to plot the data on a map or globe. If you have one coordinate system for your basemap and another for the points you are plotting, then the points will be displayed inaccurately. So, to plot the data from geocoded-police-stations.csv accurately, you'll need to find out what coordinate system is being used in the data frame, which is the canvas you're working on.

  • Go to the icon at the top of your Table of Contents that looks like interlocking rectangles and is called Layers. Right click on it and choose Properties.
  • In the tab labeled Coordinate System, look at the window labeled Current coordinate system and scroll down until the line labeled Geographic Coordinate System: and take note of what it says next to it. In this case it's GCS_North_American_1983. You'll be using this information when you map latitude and longitude from your table.

Displaying a Table's XY Data

  • Right-click on geocoded-police-station.csv in the Table of Contents view in List by Source mode and select Display XY Data
  • In the Display XY Data window that appears, go with the suggestions of Longitude as the X Field and Latitude as the Y Field.
  • For Coordinate System of Input Coordinates, click on Edit. In the Spatial Reference Properties window that pops up, use the search bar at the top to find the coordinate system you took down by looking at the data frame's properties:GCS_North_American_1983 . It's in the Geographic Coordinate Systems folder under North America. Click on it and select OK to return to the Display XY Data window.

  • If you've done this correctly, the Projected Coordinate System: NAD_1983_UTM_Zone_18N will disappear out of the Coordinate System of Input Coordinates and you'll just be left with Geographic Coordinate System: GCS_North_American_1983. Since the Projected Coordinate System's unit of measurement is meters, if you don't get rid of it as the coordinate system your ArcGIS is planning on using to plot your latitude and longitude instead of seeing those columns as degrees it will see those numbers as meters, and cluster the whole thing around the equator.

  • Click OK. You'll get a warning about an ObjectID not being present. That doesn't matter in this instance so just ignore it and click OK. 
  • A symbol will appear on your map for each of the events you plotted, and a new layer will appear in your table of contents that says geocoded-police-stations.csv Events. If you don't see the dots but the layer exists, right-click on the layer and choose Zoom to Layer and see where the points are. Then double-check that you have the right options in the Source tab of the Layer Properties window selected for the fields that correspond with latitude and longitude and coordinate systems outlined above.

The table of contents has a new layer symbolized with a dot. That dot now appears in many places across the map.

  • Spot check these to make sure they match up to the towns they're supposed to be in using the Identify tool and clicking on the new symbol and then the layer beneath it.  
  • A quick way to see if there are any glaring errors is to right-click on geocoded-police-stations.csv Events and choose Zoom to Layer. This zooms in or out until the whole layer is visible, and it will show you that a couple of these latitude and longitudes were wrong, as they appear outside of the scope of the map. A map of New York State with blue dots across it, but a few of the blue dots appear in the white space around the state

This is because I got the latitude and longitude data from these places via Google's Map API which I queried using a script and I didn't check all of the places before putting them on my map. Google's first guess for some of these places must be incorrect. Fortunately, now that I know which ones are very wrong, I can just update the csv file with the correct information for those places and repeat this procedure with the corrected sheet.

  • To see what the misidentified spots are, click on the Identify tool which is the i in a blue circle on the menu bar up top and then click on each of the blue dots, writing down what the tools say the points correspond to. 

The identify tool is highlighted. Over the map there is a dialogue box that contains the information about that point

Finding Latitude and Longitude using Google Maps

  • When you have written down the information for each of these, look them up either just by searching for the police station on maps.google.com or looking for that department's website, writing down the address and putting that into Google Maps. 
  • When you successfully find the correct place in Google Maps, the latitude and longitude will be part of the URL, an example of which is highlighted here. 

A marker on a map in a web browser, above it the part of the URL directly after search term /@ is highlighted that has coordinate numbers in it

The first number is the latitude and the second is longitude.

  • Open  geocoded-police-stations.csv in Excel and update the incorrectly located police stations with the new latitude and longitude.  Save it as geocoded-police-stations2 or some other new name.
  • Right-click on the geocoded-police-stations.csv Events  and choose Remove. 
  • Repeat the same procedure with geocoded-police-stations2.csv of adding the csv file to your Table of Contents and then choosing Display XY Data from its menu. You may need to click on the folder you've stored it in in the Catalog window and choose Refresh to find the new sheet before dragging it into your Table of Contents

That will change the map to the below, where all the blue star symbols are now within the boundaries of New York. 

A map of New York state, all the blue star symbols are now only within the state borders

It'll just give you a default symbol for these events, but you can doubleclick on the symbol to change what it is. This opens the Layer Properties window, and you can change the symbol in the Symbology tab.  I'm making it a larger blue star. 

I've attached my final map below if you want to see how I configured it. 

Learning Goals

You will sometimes collect location data in the form of addresses rather than as latitude and longitude. In this case, your data will need the extra step of geocoding before you can use it in ArcGIS. Geocoding takes a location like an address or city or state and renders it as latitude and longitude coordinates so that ArcGIS or other mapping programs can read it and mark its location. 

In this exercise, you'll take a list of addresses and use the US Census Bureau's Geocoding service in order to batch process a group of addresses and get their coordinates. You'll read the output file that you receive to determine if the results you got were accurate and to take note of the addresses that the service was unable to provide. You'll find the coordinates that the gecoding service was unable to find matches for by using Google Maps. Finally you'll plot the addresses that you have found using the Display XY Data function in ArcGIS. 

It's important to note, however, that this geocoding service only works with U.S. addresses so if you are looking for addresses in foreign countries, search their government's websites to see if they provide a similar service. Additionally, it has a limit of 10,000 records so if you need more than that, you'll have to divide up your searches.

Below I've attached the csv file that you'll be using with on the US Census Bureau Geocoding website, and the map document that you'll be plotting these addresses in once you've received your coordinates.

Data

Getting Started

  • Open AddressesForGeocoding.csv in Notepad++ or the plain-text editor that you use for writing code and scripts. Notice that it is formatted as a series of lines composed of the following items, each separated by a comma: Unique ID, Number and Street Name, City, State, ZIP Code. This is because you are using a csv or comma-separated value file, rather an Excel spreadsheet. If you did want to edit this file you could do so in Excel (where you would see columns separating these values rather than commas) but you would need to save it as a CSV for it to work with the Census Geocoder
    Remember to keep this in mind for if you want to use this method to get coordinates for your own list of addresses. You can still feed in these values if you are missing a city or zip code for one of your addresses, as long as you leave a blank column (or space between commas) for that value.
  • Close AddressesForGeocoding.csv
  • Go to the Census Geocoder online at https://geocoding.geo.census.gov/geocoder/ and choose the option on the left side menu that you'd like to Find Geographies Using... Address Batch. This will bring you to a page where you can upload your csv file. and the geocoder will use the Census's Master Address File to provide the latitude and longitude for any items that it finds a definite match for or can find a probable match for based on the address ranges available within that locale. It's important to note that there is a limit of 10,000 records (or rows in your csv file) and that only U.S. addresses are available

Uploading your Address File

  • On the Address Batch page go to where it says Choose File, navigate to where you've saved  AddressesForGeocoding.csv and select it. 
  • For the options next to Benchmark and Vintage, leave the defaults selected to have it search the most recent Master Address File available. If you knew you were searching for addresses from 2010 or one of the other years and you're worried they may have changed, you could use these dropdowns to select the information from a previous year. 
  • Click on Get Results. You will see the icon in your browser tab turn into the circling line and when it finishes processing the file GeocodeResults.csv will automatically download

Working with Your Results

  • Open GeocodeResults.csv in Excel. Some of it will make some sense, you'll see the names of the police stations that you were trying to get coordinates. Some of them have Match in column C next to the address and  then what looks like coordinates in column F.  You'll notice that the addresses that were formerly spread across multiple columns are now only in Column B, and that the headers are now towards the bottom of your list in a line by themselves. But some of the others don't make as much sense. 

  • To know what these other numbers are, you'll want to consult the key available from the Census on how the results sheet is set up
    A table explaining the column contents for the results sheet
  • From a look at this sheet, it's clear that the main columns that you'll want in order to plot your items on the map are
    • 1 -  The ID (name of the police station)
    • 2 - The Address
    • 6 - Latitude,Longitude.
      However, while you are finalizing the sheet to put it in its final form, you'll still want to know which items had matches and which did not, as well as which matches were not exact so for now you'll want to keep
    • 3 - Matching Result
    • 4 - Matching Result - Exact or Not-Exact 
    • 5 - Address2: which lists the address that the census has determined is the match. This should be the same as column 2 if the match is correct, but you'll want to have it handy for those rows that are inexact matches to make sure that it hasn't found a false positive
  • Since you aren't looking for anything other than the latitude and longitude for these places, 7-12 can be taken off your sheet. However if you were looking to augment the datapoints with information about the state, county, census tract or census block that contained it, you'd leave these columns. They contain the same code that is used in other census documents for those geographic entities. So if you wanted to look and see if there was anything special about the census tracts that contained the addresses you wanted geocoding for, you'd cross-reference using column 11 (census tract code) to the information about that census tracts on other census documents. For this case, you can delete columns 7-12 (G to L) from your sheet. 
  • Right-click on the first row and choose Insert Row
  • Add in column names as follows: "LEA_Name", "Address", "Match", "Match2", "Address2", "Longitude,Latitude"
  • Highlight Column "Longitude,Latitude" and click over to Data in the menu options up top in Excel. Click on the icon Text to Columns. 
  • In the Convert Text to Columns Wizard choose the file-type as Delimited and click on Next. 
  • In the next window check the box next to Comma only as the delimiter you want it to use. Click on Finish.
  • Your Latitude and Longitude are now in separate columns
  • Delete the column towards the bottom of the sheet that contains the headers that originally existed on your sheet. 

The amount of addresses that this geocoder will give you will vary, but at least some of them aren't going to have matches depending on the kind of data you are looking for. The site acknowledges that it is better with residential vs. commercial addresses. However in this case there are only about 6 addresses out of 26 that didn't have matches, so it did have the majority. When the number is that low, it will be easy to just use Google Maps to fill in this information manually. You wouldn't want to do this for a large chunk of your data however as it is time-consuming. You could also try running it again, since I have gotten more matches a second time through than the first, but if this few records are missing matches, it will  take less time to just use Google Maps.

Using Google Maps to find Coordinates for Addresses

You probably use Google Maps quite a bit and didn't realize you were looking at coordinate data. But in fact, whenever you look up an address in Google Maps, the latitude and longitude will be right there for you in the URL. The first number after the @ is the latitude, and the second is the longitude.

A location on the map in Google Maps, and a section of the URL containing the coordinates is in the middle of it

  • For each of the addresses that you didn't receive a match, look up the address in Google Maps, and add the latitude and longitude to your GeocodeResults.csv sheet for that address. If there isn't a match for the address, (as is the case for the Adams Village Police Department) instead look up the name for the police department, then correct the address in column B (Address) to the correct address, and then change the latitude and longitude
  • When you've found the longitude and latitude for each address, delete columns Match, Match2 and Address2, and save the file as GecodedResultsForArcMap.csv to a folder you are connected to in ArcGIS. Make sure you are saving it as a csv file, and that there are no spaces in any of the headers. 

You're now set to plot your results in ArcMap

Plotting Coordinates As X,Y Data in ArcMap

  • Open New York State Base Map in ArcMap.This will put a base map of New York on your canvas to give you context of where the points you are plotting are located.

  • Using the Catalog window, navigate to the folder where you have saved GecodedResultsForArcMap.csv and drag it onto the canvas. Your map won't change since it is a table and not a shapefile, but the view in your Table of Contents window will change to the List By Source view and you'll see the file and its path displayed. 

In the previous step, you added Longitude and Latitude information to your list of addresses, and this is sufficient information for ArcMap to add a point at every coordinate spot you provide that information for, however it will need to know which coordinate system to use to do so. You'll first need to figure out what the coordinate system for your data frame is so the locations won't be distorted.

  • Go to the icon at the top of your Table of Contents that looks like interlocking rectangles and is called Layers. Right-click on it and choose Properties.
  • In the tab labeled Coordinate System, look at the window labeled Current coordinate system and scroll down until you see the line labeled Geographic Coordinate System: and take note of what it says next to it. In this case it's GCS_North_American_1983. You'll be using this information when you map latitude and longitude from your table.
  • Right-click on GeocodedResultsForArcMap.csv and choose Display XY Data.
  • In the Display XY Data window that appears, go with the suggestions of Longitude as the X Field and Latitude as the Y Field.
  • For Coordinate System of Input Coordinates, click on Edit. In the Spatial Reference Properties window that pops up, use the search bar at to find the coordinate system you took down by looking at the data frame's properties:GCS_North_American_1983 which will be in the Geographic Coordinate Systems folder under North America. Click to highlight it and select OK.
  • If you've done this correctly, the Projected Coordinate System: NAD_1983_UTM_Zone_18N will disappear out of the Coordinate System of Input Coordinates and you'll just be left with Geographic Coordinate System: GCS_North_American_1983. Since the Projected Coordinate System's unit of measurement is meters, if you don't get rid of it as the coordinate system your ArcGIS is planning on using to plot your latitude and longitude instead of seeing those columns as degrees it will see those numbers as meters, and cluster the whole thing around the equator. Your window should now look something like the below.
  • When you've selected the options described above, click OK. You'll get a warning that your Table doesn't have an ObjectID field. That doesn't relate for what you're doing today so select OK
  • After it has processed, you'll see that symbols have been added to the map in several locations around New York State, and that a new layer has been added called GeocodedResultsForArcMap.csv Events. I've changed the symbol to a larger size so that it is more evident, but it will look something like the below
    A map of New York State with red dots dispersed across it.
  • Save your map as a new title from the base map file. If you want to see how I constructed mine, it is attached below.

Learning Goals

This exercise will assume that you already have Python installed on your computer and that you have some experience using that language to query an API. I strongly recommend Codecademy  or the API exercise on Programming Historian  if either of those are not the case. I'll be explaining how to write the script that gets me this information, but I won't be explaining how to use Python or APIs in general. 

The tutorial here walks you through how I got the list that I am now using in the Plotting with Longitude and Latitude Data exercise, the list of coordinates for each of the police stations that I am mapping. I generated this using just the list of the police stations' names, the Google API and a simple Python script.

Credit here to Fred Gibbs whose script on his blog I barely had to tweak in order to write my script 

How I Got Started

  • I took the list of police departments that I got from the Department of Defense spreadsheet I was using, and put them in a separate text file.
  • I added the state abbreviation ",NY" to the end of each police station to make it easier for Google's API to find the coordinates for these stations. 
  • I saved this list as a .txt file to an easily accessible place on my computer, the same place that I was planning on saving my Python script that queries Google and the CSV file that would receive the results of that query.

Data

Writing the Script

  • Open your Python editor or Notepad ++ and proceed alongside me, the text of the script will be indented and in blue text.

This is a relatively simple script that just accesses Google Map's API, feeds it a list of names, and writes the responses that Google sends back (the longitude and latitude) into both the Python console so you can keep track of what progress you're making, and writes them to a csv file that you can later use to enter these coordinates into ArcMap. 

  • Import the modules that you'll need to use in this script

import requests
import csv
import time


'requests' is the module that allows you to make request from APIs online, and to allow Python to read information on websites, as well as convert jason material into Python objects.

'csv' is the module that lets Python interface with csv files including writing to them.

'time' lets you give instructions to Python about how much time to allot between tasks. Since you're querying an API over and over again, you'll want to give a pause in between requests so you're not putting too much strain on your servers and they hopefully won't try to kick you off because of that.

 

  • Supply your script with two important pieces of information: 
    • the file the script will be reading to give it the terms to send as a coordinates query the Google Maps API
    • the file that you'll be asking the script to put the Google Maps API's responses in.

I'll be using the variable inputfile for the former and the variable outputfile for the latter. 


inputfile = open('police-placelist.txt','r')
outputfile = csv.writer(open('geocoded-police-stations.csv','w'))


The first line is saying that when the variable inputfile is used later in the script, it's referring to the content in the file that has all your the law enforcement agency names - (police-placelist.txt) when it is read (r). Make sure you have this file in the same folder that you are saving the script to so that it can find it.

The second line is saying that the variable outputfile is the file geocoded-police-stations.csv being written to (w). 

  • Start a for-loop telling the script what to do with the names it finds in police-placelist.txt. Remember to indent after starting your for loop

for row in inputfile:
  row = row.rstrip()
  url = 'http://maps.googleapis.com/maps/api/geocode/json'
  payload = {'address':row, 'sensor':'false'}


You're first telling Python that every line in your inputfile will be called by the variable row, and then giving it a set of instructions to execute for that particular row, like r.strip() which will remove all the extra white space at the end of the row. 

Next you feed in the url for the Google Maps API and assign it to the variable 'url' which you will refer to later. 

Then you create a variable 'payload' which corresponds with a dictionary with two bits of information that the Google API will ask for: address which you're telling it to feed the API the police station name from your file (row), and sensor, which is just a metric it requires that needs to be set to true or false to function. 

  • Start a Try and Except function.
    From here the rest of the code for how to handle the results of the query could continue but I'm going to put the rest in a try and except function.
    If you proceed as a regular for-loop, then the first time the script runs into an error or a name that it can't find an address for, it will shut down and you'll have to run it again from where it left off with a whole new set of files both of the police station names and the file it writes to. No fun, right? But with try and except you're giving it alternate steps to take if there isn't an address for that URL or if there is some other error, and then move on to the next name on the list.
  • Start right below the code for the payload and put:

try:
    r = requests.get(url, params=payload)
    json = r.json()
    lat = json['results'][0]['geometry']['location']['lat']
    lng = json['results'][0]['geometry']['location']['lng']
    newrow = [row,lat,lng]


The beginning of the function that says 'try' means that this is what you're telling the script to perform if it's possible ('except' and 'else' later in the code will tell the script what to do if what you've asked it to do isn't possible)

r is a variable you're creating that just consists of Python requesting the url you've given it followed by the parameters you've given it above in the variable 'payload' (the name of the police station and the sensor being set to 'false').

Make a variable of json that is the response of your request to that API ('r') being read as a json script. 

From the whole json script the API will deliver as a response, you care about two things: the latitude and the longitude. You'll two variables to correspond with those attributes 'lat' and 'lng'. 

If you actually open the JSON script for a result from the Google Maps API query, it looks something like this

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Albuquerque",
               "short_name" : "Albuquerque",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Bernalillo County",
               "short_name" : "Bernalillo County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New Mexico",
               "short_name" : "NM",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Albuquerque, NM, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 35.2180539,
                  "lng" : -106.4711629
               },
               "southwest" : {
                  "lat" : 34.9467659,
                  "lng" : -106.881796
               }
            },
            "location" : {
               "lat" : 35.110703,
               "lng" : -106.609991
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.2180539,
                  "lng" : -106.4711629
               },
               "southwest" : {
                  "lat" : 34.9467659,
                  "lng" : -106.881796
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}
  • Look at the part highlighted in yellow in the JSON script above.
    • The latitude that you want to get is located within the larger field of "results" then in the top level family [0] of "geometry" within that group, the group "location" and then the level down from that, the field 'lat'. 
    • Same thing for longitude except for it corresponds with 'lng'

That's why you're telling it to check JSON for:

"location" : {
               "lat" : 35.110703,
               "lng" : -106.609991

}

and assigning those to the variables of lat and lng.

Last in this pack of text is the variable that refers to the information that you ultimately want to be written to the file you're creating, newrow

newrow = [row,lat,lng]

The lines that you're telling it to write to the csv is that for every place name that it gets from the txt file, to write a line to the csv with that place name, then the latitude, then the longitude. 

  • Now that you've written into your code how to get this information from the Google Maps API the next step is telling it where to write that newrow to.
  • Continuing at the same level of indent, below your newrow equation, you'd write. 

print newrow
outputfile.writerow(newrow)
time.sleep(1)


print newrow will print your results to the console window. This isn't necessary but is a good way for you to test that your script is working, and will give you a backup to consult if writing it to the file fails for some reason.

outputfile.writerow(newrowtells it to write that variable 'newrow' (the place name, the latitude and the longitude) to your output csv file that you specified way up there at the top. 

time.sleep(1) is just telling the script to wait one second before your next request to Google Maps API. If you don't include something like this it will just do it as quickly as the code executes, and the server you're requesting information from might decide to kick you off for taking up too much of its bandwidth. 

  • Go back to the same level of indentation as 'try' in your code and tell the script what to do if you get an error. 

  except IndexError:
    newrow = [row,'null','null']
    print newrow


This is telling your code, if you get an IndexError, to write out the name of the place, and for the next fields just write 'null' both to your CSV file and to the console. You can then look up the results for these (hopefully few) place names later for yourself manually. I used IndexError because that was the error I tended to get that stopped my code before I added in try and except

One more function completes this, 'else'. This tell your script what to do if it can't execute the code you put in under try but also doesn't run into the exception you put forth in except. 


  else:
    newrow = [row,'null','null']    


This is just telling your script that if it can't execute the code, and the reason isn't the one you gave it in except, then it should still write a newrow in your csv that consists of the place name, and for the latitude and longitude columns it should write null for each of them. 

I'll attach my code below if you want to see it as I wrote it, but if you've been following along in your own script editor you should be good to execute the code now. 

Troubleshooting

Caveat: even with the try and except your code might not get through the whole list before hitting something that makes it stop. I advise in that case, instead of running the whole list again -

  • Go to the first name on the list that didn't go through, copy and paste the remainder of the list including that item into a new txt file
  •  Change the inputfile in your script to be the new txt file's name, and the name of the outputfile to be a new file name or change the line

outputfile = csv.writer(open('geocoded-police-stations.csv','w'))


to be 


outputfile = csv.writer(open('geocoded-police-stations.csv','a'))


with 'w' for write switched to 'a' for append so that it doesn't overwrite the file that you've already created. 

The script should go through your list in order, so it will be easy to tell where it left off. Then you can just merge each of the csv files you get with the latitude and longitude information into one file that contains all your data. Make sure and double check to make sure that nothing is missing. Some may not be findable on the first pass and you'll need to feed through those addresses again.

Getting CSV File set for ArcGIS

  • Open geocoded-police-stations.csv in Excel.
  • Insert a row at the top and add in the that first row the header titles LEA, Latitude, Longitude. For future reference know that ArcGIS won't be able to process a CSV if the header (or field names) contain spaces, special characters or numbers at the beginning of the name

Proceed to the first exercise of this page: 'Plotting with Latitude and Longitude Data' to see how to add this data to the map.