Mapping Earthquake Data from the USGS API using Folium
Tags: python, dataviz, map, folium
Published: 2023-09-22 11:13:56

In this blog post, we will demonstrate how to visualize earthquakes with a minimum magnitude of 3 that occurred in Turkey from [February 6th](https://en.wikipedia.org/wiki/2023_Turkey%E2%80%93Syria_earthquake) to February 13th, using the API provided by the US Geological Research Institute (USGS).

Let's import the required libraries:

```
import requests
import pandas as pd
import folium
from folium.plugins import HeatMap
```

Here's a brief overview of these libraries:

`requests`: This versatile library allows us to perform tasks such as sending HTTP requests, fetching data from the internet, accessing web pages, and connecting to APIs.

`pandas`: It serves data analysis and processing purposes, enabling us to perform queries on datasets, filter data, merge, group, and conduct various other data-related operations.

`folium`: Folium is used for creating interactive maps and can be installed with `pip install folium`.

`folium.plugins.HeatMap`: This is an extension within the `folium` library, utilized to generate density maps.

Next, we will define the parameters for our API request:

```
start_time = '2023-02-06'
end_time = '2023-02-13'
min_magnitude = 3
latitude = 39.1458
longitude = 34.1614
max_radius_km = 1000
```

Now, let's send the HTTP request to retrieve earthquake data:

```
response = requests.get(f'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime={start_time}&minmagnitude={min_magnitude}&latitude={latitude}&longitude={longitude}&maxradiuskm={max_radius_km}')
data = response.json()
```

In this code, we use the `requests.get()` method to send a GET request to the USGS Earthquake API, constructing the URL with f-string formatting.

If the request is successful, you will receive a status code of 200, as shown below:

`<Response [200]>`

The `data` variable now contains a Python dictionary with earthquake data obtained from the USGS Earthquake API in JSON format.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjh661uxax8hagug591a.PNG)

Let's proceed by extracting the features from this data:

```
features = data['features']
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17by0m1td58iyh06smaa.PNG)

Now, we'll create various lists and populate them using a for loop:

```
places = []
mags = []
times = []
lats = []
lons = []
weights = []

for feature in features:
    places.append(feature['properties']['place'])
    mags.append(feature['properties']['mag'])
    times.append(pd.to_datetime(feature['properties']['time'], unit='ms').strftime('%y:%m:%d %H:%M:%S'))
    lats.append(feature['geometry']['coordinates'][1])
    lons.append(feature['geometry']['coordinates'][0])
    weights.append(feature['properties']['mag'])
```

In the above loop, we are extracting location, magnitude, time, latitude, longitude, and weight values from each feature and appending them to their respective lists.

Let's consolidate these lists into a DataFrame:

```
df = pd.DataFrame({
    'Place': places,
    'Magnitude': mags,
    'Time': times,
    'Latitude': lats,
    'Longitude': lons,
    'Weight': weights
})

df.tail(10)
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bz1tt2xcxjxavc1td1iy.PNG)

We now have our earthquake data organized in a DataFrame.

To visualize this data on a map, we'll proceed with the following code:

```
turkey_coord = [39, 35]
turkey_map = folium.Map(location=turkey_coord, zoom_start=5.5)
HeatMap(data=df[['Latitude', 'Longitude', 'Weight']], radius=15).add_to(turkey_map)

for index, row in df.iterrows():
    folium.CircleMarker(
        location=[row['Latitude'], row['Longitude']],
        radius=row['Magnitude']/2,
        color='red',
        fill_color='red').add_to(turkey_map)

turkey_map
```

This code is used to visualize earthquakes in Turkey and consists of the following steps:

A list named `turkey_coord` is defined, representing the center coordinates (latitude and longitude) of the map.

A map called `turkey_map` is created using the `folium.Map()` function. The initial zoom level (`zoom_start`) is set to 5.5.

A density heatmap is created using the `HeatMap()` function. This heatmap is generated from earthquake data contained in the `df` DataFrame, specifically the Latitude, Longitude, and Weight columns. The heatmap's radius is set to 15, and it is added to the `turkey_map`.

A for loop iterates over each row in the `df` DataFrame. For each earthquake, a circular marker (`folium.CircleMarker`) is created. The marker's location is determined by the Latitude and Longitude values of the earthquake. The radius of the circle is determined by the earthquake's magnitude (Magnitude) divided by 2. The color of the circle's outline and fill is set to red. These circles are then added to the turkey_map.

Finally, the `turkey_map` is displayed, making the earthquake data visually accessible.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75kws17xgrelnybv5myy.PNG)

If you wish to make the map dark, you can achieve it using the following code snippet:

```
turkey_map = folium.Map(location=turkey_coord, zoom_start=5.5, tiles='cartodbdark_matter')
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc82p9zji6lbj2u6vkwm.PNG)