Repository: jftuga/geodist
Branch: main
Commit: 3d2621e37888
Files: 10
Total size: 12.3 KB
Directory structure:
gitextract_1ubr643k/
├── .gitignore
├── LICENSE
├── README.md
├── example/
│ └── example.go
├── go.mod
├── haversine.go
├── haversine_test.go
├── shared.go
├── vincenty.go
└── vincenty_test.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
.idea/
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 John Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# geodist
GoLang package to compute the distance between two geographic latitude, longitude coordinates
## Algorithm Comparison
* `Vincenty` is more accurate than `Haversine` because is considers the Earth's [ellipticity](https://www.dictionary.com/browse/ellipticity) when performing the calculation, but takes a longer time to compute.
* [Wikipedia: Haversine](https://en.wikipedia.org/wiki/Haversine_formula)
* [Wikipedia: Vincenty](https://en.wikipedia.org/wiki/Vincenty%27s_formulae)
* [Is the Haversine Formula or the Vincenty's Formula better for calculating distance?](https://stackoverflow.com/q/38248046/452281)
## Example
* [example.go](example/example.go)
```go
var newYork = geodist.Coord{Lat: 40.7128, Lon: 74.0060}
var sanDiego = geodist.Coord{Lat: 32.7157, Lon: 117.1611}
miles, km, ok := geodist.VincentyDistance(newYork, sanDiego)
if !ok {
fmt.Println("Unable to compute Vincenty Distance.")
return
}
fmt.Printf(" [Vincenty] New York to San Diego: %.3f m, %.3f km\n", miles, km)
var elPaso = geodist.Coord{Lat: 31.7619, Lon: 106.4850}
var stLouis = geodist.Coord{Lat: 38.6270, Lon: 90.1994}
miles, km = geodist.HaversineDistance(elPaso, stLouis)
fmt.Printf("[Haversine] El Paso to St. Louis: %.3f m, %.3f km\n", miles, km)
```
## Online Calculators
* **Great Circle**: [NOAA: Latitude/Longitude Distance Calculator](https://www.nhc.noaa.gov/gccalc.shtml)
* **Haversine**: [Moveable Type: Calculate distance, bearing and more between Latitude/Longitude points](https://www.movable-type.co.uk/scripts/latlong.html)
* **Vincenty**: [CQSRG: WGS-84 World Geodetic System Distance Calculator](https://www.cqsrg.org/tools/GCDistance/)
## Acknowledgements
* [Haversine Algorithm](https://gist.github.com/cdipaolo/d3f8db3848278b49db68) in `GoLang`
* [Vincenty Algorithm](https://web.archive.org/web/20181109001358/http://www.5thandpenn.com/GeoMaps/GMapsExamples/distanceComplete2.html) in `JavaScript`
================================================
FILE: example/example.go
================================================
package main
import (
"fmt"
"github.com/jftuga/geodist"
)
func main() {
var newYork = geodist.Coord{Lat: 40.7128, Lon: 74.0060}
var sanDiego = geodist.Coord{Lat: 32.7157, Lon: 117.1611}
miles, km, err := geodist.VincentyDistance(newYork, sanDiego)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf(" [Vincenty] New York to San Diego: %.3f m, %.3f km\n", miles, km)
miles, km = geodist.HaversineDistance(newYork, sanDiego)
fmt.Printf("[Haversine] New York to San Diego: %.3f m, %.3f km\n", miles, km)
fmt.Println()
var elPaso = geodist.Coord{Lat: 31.7619, Lon: 106.4850}
var stLouis = geodist.Coord{Lat: 38.6270, Lon: 90.1994}
miles, km, err = geodist.VincentyDistance(elPaso, stLouis)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf(" [Vincenty] El Paso to St. Louis: %.3f m, %.3f km\n", miles, km)
miles, km = geodist.HaversineDistance(elPaso, stLouis)
fmt.Printf("[Haversine] El Paso to St. Louis: %.3f m, %.3f km\n", miles, km)
}
================================================
FILE: go.mod
================================================
module github.com/jftuga/geodist
go 1.17
================================================
FILE: haversine.go
================================================
/*
haversine.go
-John Taylor
Compute the distance between two geographic points when given a pair of latitude-longitude coordinates
Haversine formula:
https://en.wikipedia.org/wiki/Haversine_formula
The code below was adapted from Conner DiPaolo:
https://gist.github.com/cdipaolo/d3f8db3848278b49db68
*/
package geodist
import (
"math"
)
// adapted from: https://gist.github.com/cdipaolo/d3f8db3848278b49db68
// haversin(θ) function
func hsin(theta float64) float64 {
return math.Pow(math.Sin(theta/2), 2)
}
// HaversineDistance returns the distance (in miles) between two points of
// a given longitude and latitude relatively accurately (using a spherical
// approximation of the Earth) through the Haversin Distance Formula for
// great arc distance on a sphere with accuracy for small distances
//
// point coordinates are supplied in degrees and converted into rad. in the func
//
// http://en.wikipedia.org/wiki/Haversine_formula
func HaversineDistance(p1, p2 Coord) (float64, float64) {
// convert to radians
// must cast radius as float to multiply later
var la1, lo1, la2, lo2, r float64
piRad := math.Pi / 180
la1 = p1.Lat * piRad
lo1 = p1.Lon * piRad
la2 = p2.Lat * piRad
lo2 = p2.Lon * piRad
r = 6378100 // Earth radius in METERS
// calculate
h := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1)
meters := 2 * r * math.Asin(math.Sqrt(h))
kilometers := meters / 1000
miles := kilometers * 0.621371
return miles, kilometers
}
================================================
FILE: haversine_test.go
================================================
package geodist
import (
"testing"
)
func TestHaversineDistance(t *testing.T) {
// distance NY-SD: 3915340.577 m
// distance SD-EP: 1011300.217 m
// distance EP-SL: 1663833.491 m
// distance SL-NY: 1406519.972 m
var newYork = Coord{40.7128, 74.0060}
var sanDiego = Coord{32.7157, 117.1611}
var elPaso = Coord{31.7619, 106.4850}
var stLouis = Coord{38.6270, 90.1994}
var miles, km float64
miles, km = HaversineDistance(newYork, sanDiego)
if int(miles) != 2430 || int64(km) != 3911 {
t.Errorf("Computed values: %v %10f\n", miles, km)
t.Errorf("Incorrect computation between New York and San Diego: %v %v\n", int(miles), int64(km))
}
miles, km = HaversineDistance(sanDiego, elPaso)
if int(miles) != 627 || int64(km) != 1010 {
t.Errorf("Computed values: %v %10f\n", miles, km)
t.Errorf("Incorrect computation between San Diego and El Paso: %v %v\n", int(miles), int64(km))
}
miles, km = HaversineDistance(elPaso, stLouis)
if int(miles) != 1033 || int(km) != 1663 {
t.Errorf("Computed values: %v %10f\n", miles, km)
t.Errorf("Incorrect computation between El Paso and St. Louis: %v %v\n", int(miles), int64(km))
}
miles, km = HaversineDistance(stLouis, newYork)
if int(miles) != 872 || int(km) != 1404 {
t.Errorf("Computed values: %v %10f\n", miles, km)
t.Errorf("Incorrect computation between St. Louis and New York: %v %v\n", int(miles), int64(km))
}
miles, km = HaversineDistance(newYork, newYork)
if int(miles) != 0 || int(km) != 0 {
t.Errorf("Computed values: %v %10f\n", miles, km)
t.Errorf("Incorrect computation between New York and New York: %v %v\n", int(miles), int64(km))
}
}
================================================
FILE: shared.go
================================================
/*
shared.go
-John Taylor
shared components between the distance algorithms
*/
package geodist
const version string = "1.0.0"
// Coord represents a geographic coordinate
type Coord struct {
Lat float64
Lon float64
}
================================================
FILE: vincenty.go
================================================
/*
vincenty.go
-John Taylor
Compute the distance between two geographic points when given a pair of latitude-longitude coordinates
Vincenty formula:
https://en.wikipedia.org/wiki/Vincenty%27s_formulae
The code below was ported from Chris Veness's JavaScript version:
https://web.archive.org/web/20181109001358/http://www.5thandpenn.com/GeoMaps/GMapsExamples/distanceComplete2.html
*/
package geodist
import (
"errors"
"math"
)
// these constants are used for vincentyDistance()
// reference: https://en.wikipedia.org/wiki/World_Geodetic_System#1984_version
const a = 6378137
const b = 6356752.3142
const f = 1 / 298.257223563 // WGS-84 ellipsiod
/*
VincentyDistance computes the distances between two georgaphic coordinates
Args:
p1: the 'starting' point, given in latitude, longitude as a Coord struct
p2: the 'ending' point
Returns:
A 3 element tuple: distance between the 2 points given in (1) miles and (2) kilometers
The 3rd element will return true upon a successful computation or
false if the algorithm fails to converge. -1, -1, false is returned upon failure
*/
func VincentyDistance(p1, p2 Coord) (float64, float64, error) {
// convert from degrees to radians
piRad := math.Pi / 180
p1.Lat = p1.Lat * piRad
p1.Lon = p1.Lon * piRad
p2.Lat = p2.Lat * piRad
p2.Lon = p2.Lon * piRad
L := p2.Lon - p1.Lon
U1 := math.Atan((1 - f) * math.Tan(p1.Lat))
U2 := math.Atan((1 - f) * math.Tan(p2.Lat))
sinU1 := math.Sin(U1)
cosU1 := math.Cos(U1)
sinU2 := math.Sin(U2)
cosU2 := math.Cos(U2)
lambda := L
lambdaP := 2 * math.Pi
iterLimit := 20
var sinLambda, cosLambda, sinSigma float64
var cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM, C float64
for {
if math.Abs(lambda-lambdaP) > 1e-12 && (iterLimit > 0) {
iterLimit -= 1
} else {
break
}
sinLambda = math.Sin(lambda)
cosLambda = math.Cos(lambda)
sinSigma = math.Sqrt((cosU2*sinLambda)*(cosU2*sinLambda) + (cosU1*sinU2-sinU1*cosU2*cosLambda)*(cosU1*sinU2-sinU1*cosU2*cosLambda))
if sinSigma == 0 {
return 0, 0, nil // co-incident points
}
cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda
sigma = math.Atan2(sinSigma, cosSigma)
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma
cosSqAlpha = 1 - sinAlpha*sinAlpha
cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha
if math.IsNaN(cos2SigmaM) {
cos2SigmaM = 0 // equatorial line: cosSqAlpha=0
}
C = f / 16 * cosSqAlpha * (4 + f*(4-3*cosSqAlpha))
lambdaP = lambda
lambda = L + (1-C)*f*sinAlpha*(sigma+C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)))
}
if iterLimit == 0 {
return -1, -1, errors.New("vincenty algorithm failed to converge") // formula failed to converge
}
uSq := cosSqAlpha * (a*a - b*b) / (b * b)
A := 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)))
B := uSq / 1024 * (256 + uSq*(-128+uSq*(74-47*uSq)))
deltaSigma := B * sinSigma * (cos2SigmaM + B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)))
meters := b * A * (sigma - deltaSigma)
kilometers := meters / 1000
miles := kilometers * 0.621371
return miles, kilometers, nil
}
================================================
FILE: vincenty_test.go
================================================
package geodist
import (
"testing"
)
func TestVincentyDistance(t *testing.T) {
// distance NY-SD: 3915340.577 m
// distance SD-EP: 1011300.217 m
// distance EP-SL: 1663833.491 m
// distance SL-NY: 1406519.972 m
var newYork = Coord{40.7128, 74.0060}
var sanDiego = Coord{32.7157, 117.1611}
var elPaso = Coord{31.7619, 106.4850}
var stLouis = Coord{38.6270, 90.1994}
var miles, km float64
var err error
miles, km, err = VincentyDistance(newYork, sanDiego)
if int(miles) != 2432 || int64(km) != 3915 || err != nil {
t.Errorf("Computed values: %v %10f %v\n", miles, km, err)
t.Errorf("Incorrect computation between New York and San Diego: %v %v %v\n", int(miles), int64(km), err)
}
miles, km, err = VincentyDistance(sanDiego, elPaso)
if int(miles) != 628 || int64(km) != 1011 || err != nil {
t.Errorf("Computed values: %v %10f %v\n", miles, km, err)
t.Errorf("Incorrect computation between San Diego and El Paso: %v %v %v\n", int(miles), int64(km), err)
}
miles, km, err = VincentyDistance(elPaso, stLouis)
if int(miles) != 1033 || int(km) != 1663 || err != nil {
t.Errorf("Computed values: %v %10f %v\n", miles, km, err)
t.Errorf("Incorrect computation between El Paso and St. Louis: %v %v %v\n", int(miles), int64(km), err)
}
miles, km, err = VincentyDistance(stLouis, newYork)
if int(miles) != 873 || int(km) != 1406 || err != nil {
t.Errorf("Computed values: %v %10f %v\n", miles, km, err)
t.Errorf("Incorrect computation between St. Louis and New York: %v %v %v\n", int(miles), int64(km), err)
}
miles, km, err = VincentyDistance(newYork, newYork)
if int(miles) != 0 || int(km) != 0 || err != nil {
t.Errorf("Computed values: %v %10f %v\n", miles, km, err)
t.Errorf("Incorrect computation between New York and New York: %v %v %v\n", int(miles), int64(km), err)
}
}
gitextract_1ubr643k/ ├── .gitignore ├── LICENSE ├── README.md ├── example/ │ └── example.go ├── go.mod ├── haversine.go ├── haversine_test.go ├── shared.go ├── vincenty.go └── vincenty_test.go
SYMBOL INDEX (11 symbols across 6 files)
FILE: example/example.go
function main (line 8) | func main() {
FILE: haversine.go
function hsin (line 24) | func hsin(theta float64) float64 {
function HaversineDistance (line 36) | func HaversineDistance(p1, p2 Coord) (float64, float64) {
FILE: haversine_test.go
function TestHaversineDistance (line 7) | func TestHaversineDistance(t *testing.T) {
FILE: shared.go
constant version (line 11) | version string = "1.0.0"
type Coord (line 14) | type Coord struct
FILE: vincenty.go
constant a (line 25) | a = 6378137
constant b (line 26) | b = 6356752.3142
constant f (line 27) | f = 1 / 298.257223563
function VincentyDistance (line 42) | func VincentyDistance(p1, p2 Coord) (float64, float64, error) {
FILE: vincenty_test.go
function TestVincentyDistance (line 7) | func TestVincentyDistance(t *testing.T) {
Condensed preview — 10 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (14K chars).
[
{
"path": ".gitignore",
"chars": 276,
"preview": "# Binaries for programs and plugins\n*.exe\n*.exe~\n*.dll\n*.so\n*.dylib\n\n# Test binary, built with `go test -c`\n*.test\n\n# Ou"
},
{
"path": "LICENSE",
"chars": 1068,
"preview": "MIT License\n\nCopyright (c) 2021 John Taylor\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
},
{
"path": "README.md",
"chars": 1932,
"preview": "# geodist\nGoLang package to compute the distance between two geographic latitude, longitude coordinates\n\n## Algorithm Co"
},
{
"path": "example/example.go",
"chars": 972,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/jftuga/geodist\"\n)\n\nfunc main() {\n\tvar newYork = geodist.Coord{Lat: 40.7128, L"
},
{
"path": "go.mod",
"chars": 42,
"preview": "module github.com/jftuga/geodist\n\ngo 1.17\n"
},
{
"path": "haversine.go",
"chars": 1479,
"preview": "/*\n\nhaversine.go\n-John Taylor\n\nCompute the distance between two geographic points when given a pair of latitude-longitud"
},
{
"path": "haversine_test.go",
"chars": 1636,
"preview": "package geodist\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHaversineDistance(t *testing.T) {\n\t// distance NY-SD: 3915340.577 m\n\t//"
},
{
"path": "shared.go",
"chars": 223,
"preview": "/*\nshared.go\n-John Taylor\n\nshared components between the distance algorithms\n\n*/\n\npackage geodist\n\nconst version string "
},
{
"path": "vincenty.go",
"chars": 3124,
"preview": "/*\n\nvincenty.go\n-John Taylor\n\nCompute the distance between two geographic points when given a pair of latitude-longitude"
},
{
"path": "vincenty_test.go",
"chars": 1820,
"preview": "package geodist\n\nimport (\n\t\"testing\"\n)\n\nfunc TestVincentyDistance(t *testing.T) {\n\t// distance NY-SD: 3915340.577 m\n\t// "
}
]
About this extraction
This page contains the full source code of the jftuga/geodist GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 10 files (12.3 KB), approximately 4.3k tokens, and a symbol index with 11 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.