Skip to content

Instantly share code, notes, and snippets.

@PietrH
Last active January 30, 2025 15:02
Show Gist options
  • Save PietrH/6788668e17ec93d75fb94cc63beceb5b to your computer and use it in GitHub Desktop.
Save PietrH/6788668e17ec93d75fb94cc63beceb5b to your computer and use it in GitHub Desktop.
Example usage of iNaturalist API to create leaflet map for a taxon within radius of a point
get_inat_obs_radius <- function(taxon_id, lat, lng, radius) {
api_response <- httr2::request(
"https://api.inaturalist.org/v1/observations/"
) %>%
httr2::req_url_query(
taxon_id = taxon_id,
lat = lat,
lng = lng,
radius = radius
) %>%
httr2::req_retry() %>%
httr2::req_perform() %>%
httr2::resp_body_json(simplifyVector = TRUE)
tibble::as_tibble(api_response$results)
}
get_inat_obs_radius(
taxon_id=157924,
lat=50.86190,
lng=4.36038,
radius=50
)
create_inat_leaflet_map <- function(taxon_id, lat, lng, radius) {
# 1. Fetch observations
observations <- get_inat_obs_radius(
taxon_id = taxon_id,
lat = lat,
lng = lng,
radius = radius
)
# 2. Extract lat/lon from the geojson column
observations_map_data <-
observations %>%
dplyr::mutate(
lon = purrr::map_dbl(.data$geojson$coordinates, ~ purrr::chuck(.x, 1)),
lat = purrr::map_dbl(.data$geojson$coordinates, ~ purrr::chuck(.x, 2))
)
# 3. Make a map
leaflet::leaflet(observations_map_data) %>%
leaflet::addTiles() %>%
leaflet::addMarkers(
lng = ~lon,
lat = ~lat
)
}
create_inat_leaflet_map(
taxon_id=157924,
lat=50.86190,
lng=4.36038,
radius=50
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment