From API to Map: USGS Earthquake Data

DATA 607 | Discussion 7 | API Video Explainer

Author

Sarah Abdelrahman

CUNY School of Professional Studies | M.S. in Data Science
Course: DATA 607 — Data Acquisition and Management
Instructor: Professor Darwhin Gomez

1. Why geospatial APIs matter

An application programming interface (API) enables software to request data from another system. The United States Geological Survey (USGS) provides public earthquake feeds that allow analysts to retrieve recent seismic observations without manually downloading spreadsheets. This demonstration connects GIS and data science through an HTTP GET request, JSON parsing, data cleaning and interactive mapping.

Objective: Retrieve earthquakes of magnitude 2.5 or greater reported worldwide during the past seven days and visualize their locations.

2. Workflow

USGS API → HTTP GET → GeoJSON → tidy R table → spatial features → interactive map.

Install the required packages once in the RStudio console:

install.packages(c("httr2", "jsonlite", "dplyr", "sf", "leaflet", "ggplot2", "knitr", "htmltools"))
library(httr2)
library(jsonlite)
library(dplyr)
library(sf)
library(leaflet)
library(ggplot2)

3. Make an API request

The endpoint below is a public rolling feed and requires no API key. HTTP GET retrieves the resource; a successful response normally has status 200.

url <- "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson"
response <- request(url) |>
  req_timeout(60) |>
  req_retry(max_tries = 3) |>
  req_perform()
resp_check_status(response)
resp_status(response)
[1] 200
raw <- resp_body_string(response)
feed <- fromJSON(raw, flatten = TRUE)
cat("Retrieved at (UTC):", format(Sys.time(), tz = "UTC"), "\n")
Retrieved at (UTC): 2026-11-29 08:49:43 
cat("Reported events:", feed$metadata$count)
Reported events: 383

4. Understand and transform GeoJSON

GeoJSON represents each event as a feature containing properties and point geometry. USGS coordinates are ordered longitude, latitude, depth in kilometers. Event times are milliseconds since the Unix epoch.

features <- feed$features
if (is.null(features) || nrow(features) == 0) stop("No events returned by the feed.")
coords <- features$geometry.coordinates
quakes <- tibble(
  id = features$id,
  place = features$properties.place,
  magnitude = features$properties.mag,
  time_utc = as.POSIXct(features$properties.time / 1000,
                       origin = "1970-01-01", tz = "UTC"),
  longitude = vapply(coords, function(x) x[1], numeric(1)),
  latitude = vapply(coords, function(x) x[2], numeric(1)),
  depth_km = vapply(coords, function(x) x[3], numeric(1)),
  type = features$properties.type
) |>
  filter(type == "earthquake", is.finite(magnitude), magnitude >= 2.5,
         between(longitude, -180, 180), between(latitude, -90, 90)) |>
  distinct(id, .keep_all = TRUE)
if (nrow(quakes) == 0) stop("No valid earthquakes after filtering.")
knitr::kable(head(select(quakes, place, magnitude, depth_km, time_utc), 8),
             digits = 2, caption = "Sample earthquake records")
Sample earthquake records
place magnitude depth_km time_utc
5 km SW of Manhattan Beach, CA 2.99 12.49 2026-11-29 08:42:39
central Mid-Atlantic Ridge 5.30 10.00 2026-11-29 07:34:59
119 km S of Pýrgos, Greece 4.20 35.88 2026-11-29 06:49:25
18 km NNW of Camuy, Puerto Rico 2.78 15.79 2026-11-29 06:47:57
5 km SW of Lakeside, Montana 3.80 22.00 2026-11-29 05:10:10
6 km WSW of Hermosa Beach, CA 3.33 12.50 2026-11-29 05:07:20
57 km SSW of Wakefield, New Zealand 4.30 83.63 2026-11-29 04:59:50
182 km NW of Tobelo, Indonesia 4.90 35.00 2026-11-29 04:54:24

5. Analyze the observations

quakes |>
  summarise(events = n(), strongest_magnitude = max(magnitude),
            median_magnitude = median(magnitude),
            median_depth_km = median(depth_km, na.rm = TRUE)) |>
  knitr::kable(digits = 2)
events strongest_magnitude median_magnitude median_depth_km
372 6.7 3.26 15.58
ggplot(quakes, aes(magnitude)) +
  geom_histogram(binwidth = 0.25, boundary = 2.5, fill = "#176B87", color = "white") +
  labs(title = "Earthquake magnitude distribution", x = "Magnitude", y = "Events") +
  theme_minimal()

6. Build an interactive earthquake map

Convert longitude and latitude into spatial points using WGS 84 (EPSG:4326). Marker size and color represent magnitude; clicking a marker reveals the event details.

spatial_quakes <- st_as_sf(quakes, coords = c("longitude", "latitude"),
                           crs = 4326, remove = FALSE)
pal <- colorBin("YlOrRd", domain = quakes$magnitude,
                bins = c(2.5, 4, 5, 6, 7, Inf))
leaflet(spatial_quakes) |>
addTiles() |>
  setView(lng = 0, lat = 15, zoom = 2) |>
  addCircleMarkers(radius = ~3 + 2 * (magnitude - 2.5),
                   color = ~pal(magnitude), fillOpacity = 0.8,
                   stroke = FALSE,
                   popup = ~paste0("<b>", htmltools::htmlEscape(place), "</b>",
                                   "<br>Magnitude: ", magnitude,
                                   "<br>Depth (km): ", depth_km,
                                   "<br>UTC: ", format(time_utc, tz = "UTC"))) |>
  addLegend(position = "bottomright", pal = pal, values = ~magnitude,
            title = "Magnitude", opacity = 1)

7. Interpretation and limitations

The map supports exploration of where recent earthquakes occurred and how their magnitudes differ. Emergency management and environmental monitoring are potential applications. However, this rolling feed changes over time, observations can be revised, detection coverage varies, and a short observation window is not a reliable estimate of long-term seismic risk. The map does not predict future earthquakes. Internet access is required to retrieve the feed and display online map tiles.

8. References

Course: DATA 607 – Data Acquisition and Management | Instructor: Professor Darwhin Gomez | Fall 2026.