Downloading data from OpenStreetMap with R

Surely, it must be possible to create your own map based on data from OpenStreetMap using R? Perhaps a map with all of the restaurants in your area? This script will:

  • Create a query
  • Download data from OpenStreetMap using the query
  • Clean the data
  • View the data on a web map and the the result to a html file

# Load libraries
library(dplyr)
library(htmlwidgets)
library(leaflet)
library(osmdata)
library(sf)

# Set working directory
setwd(“C:\\R\\”)

# Build a query and fetch data from OpenStreetMap
query <- opq(bbox = “gothenburg, sweden”) |>
add_osm_feature(key = “amenity”, value = “restaurant”)
restaurants_gothenburg <- osmdata_sf(query)

# Filter restaurants
point_restaurants_gothenburg <- restaurants_gothenburg$osm_points |>
filter(amenity == “restaurant”)

# Polygons to points, since both polygons and points are extracted from OpenStreetMap
centroid_restaurants_gothenburg <- restaurants_gothenburg$osm_polygons |>
st_centroid()

# Combine the two point data sets
all_restaurants_gothenburg <- bind_rows(point_restaurants_gothenburg, centroid_restaurants_gothenburg)

# Only keep osm_id and name
all_restaurants_gothenburg = select(all_restaurants_gothenburg, osm_id, name)

# View route on Leaflet map
gothenburg_restaurants = leaflet() %>%
addTiles() %>%
addMarkers(data=all_restaurants_gothenburg, popup = ~as.character(name), label = ~as.character(name), group = “Restaurants”) %>%

# Layer control
addLayersControl(
overlayGroups = c(“Restaurants”),
options = layersControlOptions(collapsed = FALSE)
)

# Save map to disk
saveWidget(widget = gothenburg_restaurants, file = “Gothenburg_restaurants.html”)

That´s it. But what if you find errors in the data? Then it´s time to contribute to the project and improve the map. The script is partially based on https://rpubs.com/stragu/sotm2021.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait