Example 1: sf objects
The following example shows how to create a static map using data retrieved with arcgeocoder and converted to an sf object:
library(arcgeocoder)
library(dplyr)
library(sf) # Spatial objects.
library(ggplot2)
library(mapSpain) # **sf** objects of Spain.
# McDonald's restaurants in Barcelona, Spain.
mc <- arc_geo_multi(
"McDonalds",
city = "Barcelona",
region = "Catalonia",
countrycode = "ES",
category = "Food",
limit = 50,
custom_query = list(outFields = c("LongLabel", "Type", "StAddr"))
)
# Convert to an **sf** object.
mc_sf <- st_as_sf(
mc,
coords = c("lon", "lat"),
# Use the WKID from the geocoding results.
crs = mc$latestWkid[1]
)
bcn <- esp_get_munic(munic = "Barcelona") |>
st_transform(mc$latestWkid[1])
ggplot(bcn) +
geom_sf() +
geom_sf(data = mc_sf, color = "red")
# Restrict results to the Barcelona bounding box in the query.
bbox <- st_bbox(bcn) |> paste0(collapse = ",")
bbox
#> [1] "2.0536216,41.3217545,2.227167,41.467717"
mc2_sf <- arc_geo_multi(
"McDonalds",
city = "Barcelona",
region = "Catalonia",
countrycode = "ES",
category = "Food",
limit = 50,
custom_query = list(
outFields = c("LongLabel", "Type", "StAddr"),
searchExtent = bbox
)
) |>
st_as_sf(coords = c("lon", "lat"), crs = mc$latestWkid[1])
ggplot(bcn) +
geom_sf() +
geom_sf(data = mc2_sf, color = "red")
Example 2: terra objects
We can add static map tiles with the maptiles package and use the tidyterra package for plotting. The tiles are represented here as terra objects: