Skip to content
R for the Rest of Us Logo

Mapping with R

Geocoding

Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

View code shown in video
library(sf)

library(tidyverse)

famous_places <-
  tribble(
    ~building,
    ~address,
    "White House",
    "1600 Pennsylvania Ave NW, Washington, DC 20500 United States",
    "Empire State Building",
    "350 5th Ave, New York, NY 10118, USA"
  )

library(tidygeocoder)

famous_places |>
  geocode(address)

famous_places_sf <-
  famous_places |>
  geocode(address) |>
  st_as_sf(
    coords = c("long", "lat"),
    crs = 4326
  )

famous_places_sf

famous_places_sf |>
  mapview::mapview()

us_and_uk_head_residences <-
  tribble(
    ~building,
    ~address,
    "White House",
    "1600 Pennsylvania Ave NW, Washington, DC 20500 United States",
    "Number 10",
    "10 Downing St, London SW1A 2AA, United Kingdom"
  )

us_and_uk_head_residences

us_and_uk_head_residences |>
  geocode(address)

us_and_uk_head_residences |>
  geocode(
    address,
    method = "iq"
  )

us_and_uk_head_residences_v2 <-
  tribble(
    ~building,
    ~address,
    ~city,
    ~state,
    ~postal_code,
    ~country,
    "White House",
    "1600 Pennsylvania Ave NW",
    "Washington",
    "DC",
    "20500",
    "United States",
    "Number 10",
    "10 Downing St",
    "London",
    NA,
    "SW1A 2AA",
    "United Kingdom"
  )

us_and_uk_head_residences_v2 |>
  geocode(
    street = address,
    city = city,
    state = state,
    postalcode = postal_code,
    country = country
  )

us_and_uk_head_residences_v2 |>
  geocode(
    street = address,
    city = city,
    state = state,
    postalcode = postal_code,
    country = country,
    method = "iq"
  )

Your Turn

Create a tibble with the following starter code for your home address:

library(tidyverse)

my_address <-
  tribble(
    ~address,
    "Your address goes here"
  )

Use the {tidygeocoder} package to geocode your address

Turn the result into an sf object with st_as_sf() and plot it on a map with mapview::mapview() to make sure it worked

Remember that if you want to use method = "iq" you’ll need to sign up for a free LocationIQ account and create an API key

Learn More

To learn more about {tidygeocoder}, check out its documentation website.

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.