The Go language method for calculating the distance between two degrees of longitude and latitude

  • 2020-05-12 02:46:32
  • OfStack

This article illustrates an example of how the Go language calculates the distance between two degrees of longitude and latitude. Share with you for your reference. The specific implementation method is as follows:

package main
      
import (
    "fmt"
    "math"
)
      
func main() {
    lat1 := 29.490295
    lng1 := 106.486654
      
    lat2 := 29.615467
    lng2 := 106.581515
    fmt.Println(EarthDistance(lat1, lng1, lat2, lng2))
}
      
func EarthDistance(lat1, lng1, lat2, lng2 float64) float64 {
    radius := 6371000 // 6378137
    rad := math.Pi/180.0
          
    lat1 = lat1 * rad
    lng1 = lng1 * rad
    lat2 = lat2 * rad
    lng2 = lng2 * rad
          
    theta := lng2 - lng1
    dist := math.Acos(math.Sin(lat1) * math.Sin(lat2) + math.Cos(lat1) * math.Cos(lat2) * math.Cos(theta))
          
    return dist * radius
}

I hope this article has been helpful to your programming of Go language.


Related articles: