R
geo
Published

July 14, 2024

Geocoding in R

Geocoding of places in R with the tidygeocoder package using the OpenStreetMap Nominatim API and creating a sf geometry list-column.

library(tidyverse)
library(sf)

places <-
  tibble(
    city = c(
      "Berlin", "Bremen", "Bielefeld", "Dortmund", "Dresden", "Flensburg", "Frankfurt",
      "Freiburg", "Hamburg", "Hannover", "Kassel", "Köln", "Konstanz", "Leipzig",
      "Magdeburg", "München", "Passau", "Rostock", "Trier", "Nürnberg", "Stuttgart"
    )
  )

places <-
  places |>
  tidygeocoder::geocode(city, method = "osm") |>
  st_as_sf(crs = "EPSG:4326", coords = c("long", "lat"), na.fail = FALSE)

write_rds(places, "deu-cities_sf.rds")
Code
library(tidyverse)

# use data in rds-file to avoid geocoding request of 20s
places <- read_rds("deu-cities_sf.rds")

ggplot() +
  geom_sf_label(data = places, aes(label = city)) +
  coord_sf(crs = "EPSG:4839") + # LLC projection Germany
  theme_void()