DEV Community

Christopher Konopka
Christopher Konopka

Posted on

Get daily earthquake data from the USGS using Go

logo

Recently I started an earthquake sonification project and the first step is acquiring daily earthquake magnitudes from the USGS.

Use the USGS URL below, open a browser and go to the following link. Note the starttime and endtime determine the date range of the results.

https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-01-02

A large JSON response is returned, but for the purposes of the post a shorter version is provided. The goal is to access the Place and Magnitude values from the properties object inside the features object.

{
    "type": "FeatureCollection",
    "metadata": {
        "generated": 1578386362000,
        "url": "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-01-02",
        "title": "USGS Earthquakes",
        "status": 200,
        "api": "1.8.1",
        "count": 324
    },
    "features": [{
        "type": "Feature",
        "properties": {
            "mag": 1.29,
            "place": "10km SSW of Idyllwild, CA",
            "time": 1388620296020,
            "updated": 1457728844428,
            "tz": -480,
            "url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci11408890",
            "detail": "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=ci11408890&format=geojson",
            "felt": null,
            "cdi": null,
            "mmi": null,
            "alert": null,
            "status": "reviewed",
            "tsunami": 0,
            "sig": 26,
            "net": "ci",
            "code": "11408890",
            "ids": ",ci11408890,",
            "sources": ",ci,",
            "types": ",cap,focal-mechanism,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,",
            "nst": 39,
            "dmin": 0.067290000000000003,
            "rms": 0.089999999999999997,
            "gap": 51,
            "magType": "ml",
            "type": "earthquake",
            "title": "M 1.3 - 10km SSW of Idyllwild, CA"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-116.7776667, 33.663333299999998, 11.007999999999999]
        },
        "id": "ci11408890"
    }]
}

Use JSON-to-Struct to create a struct from the JSON response. A modified version is added below that focuses on the earthquake's Place and Magnitude.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

type usgsJSON struct {
    Features []feature `json:"features"`
}

type feature struct {
    Properties Earthquake `json:"properties"`
}

type Earthquake struct {
    Place     string  `json:"place"`
    Magnitude float64 `json:"mag"`
}

func main(){
     // insert code here
}

Get the current date.

current := time.Now()
currentFormat := current.Format("2006-01-02")

Get yesterdays date.

yesterdayTime := time.Now().Add(-24 * time.Hour)
yesterFormat := yesterdayTime.Format(("2006-01-02"))

Construct the USGS URL for the GET request using the currentFormat and yesterFormat.

findHawaiianVolcanos := "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=" + yesterFormat + "&endtime=" + currentFormat

Perform a GET request.

resp, err := http.Get(findHawaiianVolcanos)
if err != nil {}

Read the data until EOF and return the data to the body variable.

body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()

Unmarshal the body into usgsJSON struct.

var record usgsJSON
json.Unmarshal(body, &record)

Make a slice of "Earthquake" of length 0.

quakes := make([]Earthquake, 0)

Iterate over each "features" object and append the "properties" object to the quakes slice.

for _, f := range record.Features {
    quakes = append(quakes, f.Properties)
}

Iterate over the length of quakes and print out the magnitudes and location.

for q := 0; q < len(quakes); q++ {
    fmt.Print(quakes[q].Place + " ")
    fmt.Println(quakes[q].Magnitude)
}

Build the program.

go build usgs-dailyearthquakes.go

List the earthquakes

gif

Top comments (3)

Collapse
 
rodiongork profile image
Rodion Gorkovenko

Hi Christopher! Thanks for sharing this - though honestly it is more interesting for me due to data source of seismic events - and because I'm learning Go. Honestly I feel Go (or any compiled language) is a bit overkill for such a task. Especially usage of Json-to-Go looks horrible :)

I'll try this in PHP or Python a bit later, probably - though I suspect if you are scientist you probably tried Python for similar things already :)

Collapse
 
cskonopka profile image
Christopher Konopka

Howdy Rodion! Thanks for the response friend! :) 

I’ve tried in several languages and my preferred language is Go these days. I thought since there are not a lot of creative Go examples, it would be fun to add a few to the world. This post is part of a larger project I’m working on using the magnitude data to construct audio wavetables. There will be a second part to the series where I generate a Csound score and apply the magnitudes to the oscillators as wavetables. Currently, it sounds a little harsh, so I wanted to sweeten it up a little before I posted it. 

May be overkill, but I love Go and when I add concurrency it will make for a cool software instrument. By trade I’m a computer music researcher so I’m always looking for a unique edge to generate instruments, new HCI experiences and audio automation systems. 

Collapse
 
rodiongork profile image
Rodion Gorkovenko

Hi Christopher! Thanks for such detailed response :)

I too feel positive about Go - mainly due to its brief syntax and rich concurrency features. Can't remember other language which has messages "out of the box" besides Erlang, but it is too ancient.

Your example is quite valuable to me to learn :) so I took such a challenge - to rewrite it in scripting language as a demo of how we do this without explicit structs - and then retry doing the same in Go.

The first part is ready. Now I'll go googling for Go way to achieve similar :)

using the magnitude data to construct audio wavetables

Yep, I understand. For scientific reasons Python still may be better as it has tons of useful math/analytical libraries ready. But with Go you of course will have several times better performance (perhaps, 20 times if we mean general python interpreter)... So there are good reasons for Go of course, especially if the bulk of data is huge :)