Thanks to ohsome API and mapview, very little code is needed to make a web map visualising the evolution of building features in Kigali City on OpenStreetMap (OSM).
require(tidyverse)
require(sf)
require(rnaturalearth)
require(geojsonsf)
require(httr)
require(janitor)
require(mapview)
require(leaflet)
A bounding polygon of Kigali City can be easily acquired from Natural Earth using rnaturalearth. It is converted to GeoJSON format for the ohsome API query with geojsonsf.
bpoly <- ne_states(country = "Rwanda", returnclass = "sf") %>%
filter(name == "Kigali City") %>%
sf_geojson(digits = 5)
Now a data extraction query for yearly snapshots of building features within the boundaries of Kigali City can be posted to ohsome API. The httr package allows sending POST requests conventiently.
response <- POST(
url = "https://api.ohsome.org/v1/elements/geometry",
encode = "form",
body = list(
bpolys = bpoly,
filter = "building=* and geometry:polygon",
time = "2007-12-31/2020-12-31/P1Y"
)
)
The API’s binary response is converted first to GeoJSON text, then to simple features format. I decided to retain only building features that still existed in 2020, and selected the chronologically first version of each feature. The result is passed to mapview.
map <- response$content %>%
rawToChar() %>%
geojson_sf() %>%
clean_names() %>%
mutate(year = as.factor(str_sub(snapshot_timestamp, 1, 4))) %>%
group_by(osm_id) %>%
filter(any(year == 2020)) %>%
top_n(-1, wt = year) %>%
ungroup() %>%
mutate(osm_id = paste0(
'<a href="https://www.openstreetmap.org/', osm_id,
'" target="_blank">', osm_id, '</a>'
)) %>%
mapview(
zcol = "year", lwd = 0,
layer.name = "Feature Creation Year",
map.types = "CartoDB.DarkMatter"
)
All that’s left to do is tweaking the map a bit with leaflet for proper attribution and a nice initial view, and then grab and publish it.
map@map %>%
setView(lng = 30.09, lat = -1.95, zoom = 14) %>%
addTiles(
urlTemplate = "",
attribution = 'Made with <a href="https://docs.ohsome.org/ohsome-api/v1/" target="_blank">ohsome API</a>'
) %>%
mapshot(
url = here::here("../maps/kigali-osm-building-history/index.html"),
title = "Kigali OSM building history",
selfcontained = F
)