Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created May 15, 2013 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imjasonh/5586025 to your computer and use it in GitHub Desktop.
Save imjasonh/5586025 to your computer and use it in GitHub Desktop.
Go script to get the distance between two airports. I may someday make this an App Engine app w/ API, or accumulate multiple trips together. Sometimes I get curious how far I've flown so far this year.
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"math"
"net/http"
)
const (
r = 3958.75587 // miles
degToRad = math.Pi / 180
clientId = "TODO"
clientSecret = "TODO"
version = "20130515"
)
var (
src = flag.String("src", "", "Airport code for source")
dst = flag.String("dst", "", "Airport code for destination")
)
type latLng struct {
Lat, Lng float64
}
func main() {
flag.Parse()
fmt.Printf("%g miles", distance(*getLatLng(*src), *getLatLng(*dst)))
}
// http://en.wikipedia.org/wiki/Haversine_formula
func distance(src, dst latLng) float64 {
dLat := (src.Lat - dst.Lat) * degToRad
dLng := (src.Lng - dst.Lng) * degToRad
srcLat := src.Lat * degToRad
dstLat := dst.Lat * degToRad
a := math.Pow(math.Sin(dLat/2), 2) + math.Pow(math.Sin(dLng/2), 2)*math.Cos(srcLat)*math.Cos(dstLat)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return r * c
}
// Foursquare API response
type response struct {
Response struct {
Venues []struct {
Location latLng
}
}
}
func getLatLng(airportCode string) *latLng {
url := fmt.Sprintf(
"https://api.foursquare.com/v2/venues/search?intent=global&query=%s+airport&limit=1&client_id=%s&client_secret=%s&v=%s",
airportCode, clientId, clientSecret, version)
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
var r response
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
log.Fatal(err)
}
if len(r.Response.Venues) == 0 {
log.Fatal("Error getting airport location")
}
return &r.Response.Venues[0].Location
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment