Geocoding in R

This tutorial covers geocoding addresses into lat/long coordinates using nominatimlite.

Installing nominatimlite

You will need to install the nominatimlite package once before using it:

install.packages("nominatimlite")

Geocoding Script

The following script reads addresses from a .csv file, passes the addresses to the Nominatim API, and outputs the address data with added columns for "Latitude" and "Longitude."

The script outputs a message line for each address so you can diagnose failures.

library(nominatimlite)

address.file = "2022-lazard.csv"

address.columns = c("Address", "City", "ST", "PostalCode", "Country")

output.file = "geocoded.csv"

locations = read.csv(address.file)

for (x in 1:nrow(locations)) {
	addr = paste(locations[x, address.columns], collapse=" ")

	addr = sub("#", "number ", addr)

	latlong = geo_lite(addr, lat="latitude", long="longitude")

	locations[x, "Latitude"] = latlong$latitude

	locations[x, "Longitude"] = latlong$longitude

	print(paste(x, addr, latlong$latitude, latlong$longitude))

	write.table(locations[x,], output.file, col.names=(x == 1), 
		row.names=F, na="", append=T, sep=",")
}

Interactive Display of a CSV File with Leaflet

The Leaflet for R library that allows R to display an interactive map.

If you haven't already, you can install the Leaflet for R library with install.packages().

install.packages("leaflet")
library(leaflet)

map = leaflet()

map = addTiles(map)

markers = read.csv("geocoded.csv")

map = addMarkers(map, lng=markers$Longitude, lat=markers$Latitude,
	popup=paste0(markers$Name, "<br/>", 
	markers$Address, "<br/>", markers$City))

map
Leaflet map from .csv points