How To Find The Nearest Earthquake Event To You Using Python

Christopher Collins
3 min readOct 28, 2021

Python is a great tool for doing incredible analysis. Below I will provide the full Python code to find and map the distance of the nearest earthquake to you. You can similarly adapt this code to work with other JSON datasets that contain longitude and latitude coordinates.

When you run the code you will be asked to provide your latitude and longitude coordinate and a start and end date for the range of dates of earthquake data that you wish to check.

The result will be a map showing where all of the earth quakes that have happened in the world with a blue line showing the nearest one to your entered location.

To be able to use the code below in Jupyter Notebook or Google colab you will need to do the PIP installs for the following Python libraries:

import plotly.graph_objects as go
import json
import requests
from urllib.request import urlopen
import pandas as pd
from haversine import haversine, Unit
import numpy as np

The earthquake data is provided by the Earthquake Hazards Program https://earthquake.usgs.gov/ You can retrieve data from their website in JSON format by building a query like this.

starttime =input('Input start date range e.g. 2021-03-28')
endtime =input('Input end date range 2021-03-29')
json_url = urlopen('https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime='+ starttime +'&endtime='+endtime+'')

The full code for this project is below, but you may have to do some formats on the indentation

import plotly.graph_objects as go
import json
import requests
from urllib.request import urlopen
import pandas as pd
from haversine import haversine, Unit
import numpy as np
my_Lat = float(input('Input your latitude:'))
my_Long = float(input('Input your longitude:'))
starttime =input('Input start date range e.g. 2021-03-28')
endtime =input('Input end date range 2021-03-29')
json_url = urlopen('https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime='+ starttime +'&endtime='+endtime+'')data = json.loads(json_url.read())#for key, value in data.items() :#print (key)jdict = data.get('features')#print(jdict)latlist = []longlist = []distance_from_me = []for row in jdict:ab = row['geometry']#print(row['geometry'])#print(type(ab))rd = ab.get('coordinates')#print(rd)longitude = rd[0]latitude = rd[1]A = (latitude, longitude)B = (my_Lat, my_Long)distance = haversine(A, B)longlist.append(longitude)latlist.append(latitude)distance_from_me.append(distance)fig = go.Figure(go.Scattermapbox(name = "earthquakes",mode = "markers",lon = longlist,lat = latlist,marker= {'size': 10,'color': 'Red'},text= distance_from_me,textposition='top center'))#https://cmdlinetips.com/2018/01/how-to-create-pandas-dataframe-from-multiple-lists/data_dict = {'longitude':longlist,'latitude':latlist,'distance':distance_from_me }# Load pandas as pddf = pd.DataFrame(data_dict)column = df["distance"]min_value = column.min()#filtering pandas with locnearest_earthquake = df.loc[df['distance'] == min_value]trace_long = nearest_earthquake["longitude"]trace_lat = nearest_earthquake["latitude"]trace_long = trace_long.min()trace_lat = trace_lat.min()print('Nearest Earthquake To Me')print(min_value)print(nearest_earthquake.to_string(index=False))#showing a blue line from nearest earthquake location to meblablel = "Nearest Earthquake To Me " + str(round(min_value))fig.add_trace(go.Scattermapbox(name= blablel ,mode = "markers+lines",lon = [my_Long, trace_long],lat = [my_Lat, trace_lat],marker = {'size': 10,'color': 'Blue'},text = min_value ))#Set the zoom size of the map according to the distancezoom_size = 4if distance > 1500:zoom_size = 4if distance > 800:zoom_size = 5if distance > 600:zoom_size = 4fig.update_layout(margin ={'l':50,'t':50,'b':50,'r':300},mapbox = {'style': "stamen-terrain",'center': {'lon': my_Long, 'lat': my_Lat},'zoom': zoom_size})fig.show()

--

--

Christopher Collins

I write about coding, crypto, the tech future,please follow my publication https://medium.com/aiwriters/ 😀