Skip to Main Content

R: Mapping and Geospatial

Geospatial applications using the R programming language

Geocoding

The geocode() or mutate_geocode() function of Package 'ggmap' uses by default the Google Geocoding API. 

Google API

As of mid-2018, Google changed is terms of service to require an account to use their geocoder. You must enable the API on the Google Cloud Platform (GCP).

Obtain a GCP API key and enable services. You will need to provide a credit card number and enable billing, but you get $300 worth (or one year from initiating billing, whichever comes first) of free services (geocoding is a half-cent per address, or 60,000 free addresses). 

The API is good for other Google cloud services.

Geocoding within R

Tell ggmap about the API key using the register_google() function. Use the 'write = TRUE' argument if you want to store the key globally in R, not just for this session.

register_google(key = "[your Google API key]", write = TRUE)

Use mutate_geocode() to create a new data frame with added columns for latitude and longitude coordinates (output = "latlon" argument). output = "latlona" returns latitude, longitude, and the matched address (to cross-check against your address) as new columns.

mutate_geocode([data frame], location = [field with address], output = "latlona")

Example:

library(ggmap)
library(mapview)

addr <- data.frame(Address = c("4000 mayflower Hill, Waterville, Maine", 
                               "2 Andrews Rd, Lewiston, ME 04240",
                               "255 Maine St, Brunswick, ME 04011",
                               "90 Quaker Hill Rd, Unity, ME 04988",
                               "105 Eden St, Bar Harbor, ME 04609"),
                   College = c("Colby", "Bates", "Bowdoin", "Unity", "CoA"),
                   stringsAsFactors = FALSE)
addr.geo <- mutate_geocode(addr, location = Address, output = "latlona")

View(addr.geo)
View addr.geo

mapview(addr.geo, xcol = "lon", ycol = "lat", crs = 4269, grid = FALSE)
mapview addr.geo

[Some of example based on Intro to GIS and Spatial Analysis, Appendix III, by Manuel Gimond.]

Geocoding outside of R and Google

Alternatively, you can geocode CSV files with address data outside of R, then import the CSV with the coordinates to map the data using the read_csv() function of Package 'readr'.