routeguide: reimplement distance calculation

This commit is contained in:
Jan Tattermusch
2018-03-22 12:52:22 +01:00
parent dfbefc6795
commit 0ff1b76450

View File

@ -167,22 +167,20 @@ func toRadians(num float64) float64 {
} }
// calcDistance calculates the distance between two points using the "haversine" formula. // calcDistance calculates the distance between two points using the "haversine" formula.
// This code was taken from http://www.movable-type.co.uk/scripts/latlong.html. // The formula is based on http://mathforum.org/library/drmath/view/51879.html.
func calcDistance(p1 *pb.Point, p2 *pb.Point) int32 { func calcDistance(p1 *pb.Point, p2 *pb.Point) int32 {
const CordFactor float64 = 1e7 const CordFactor float64 = 1e7
const R float64 = float64(6371000) // metres const R float64 = float64(6371000) // earth radius in metres
lat1 := float64(p1.Latitude) / CordFactor lat1 := toRadians(float64(p1.Latitude) / CordFactor)
lat2 := float64(p2.Latitude) / CordFactor lat2 := toRadians(float64(p2.Latitude) / CordFactor)
lng1 := float64(p1.Longitude) / CordFactor lng1 := toRadians(float64(p1.Longitude) / CordFactor)
lng2 := float64(p2.Longitude) / CordFactor lng2 := toRadians(float64(p2.Longitude) / CordFactor)
φ1 := toRadians(lat1) dlat := lat2 - lat1
φ2 := toRadians(lat2) dlng := lng2 - lng1
Δφ := toRadians(lat2 - lat1)
Δλ := toRadians(lng2 - lng1)
a := math.Sin(Δφ/2)*math.Sin(Δφ/2) + a := math.Sin(dlat/2)*math.Sin(dlat/2) +
math.Cos(φ1)*math.Cos(φ2)* math.Cos(lat1)*math.Cos(lat2)*
math.Sin(Δλ/2)*math.Sin(Δλ/2) math.Sin(dlng/2)*math.Sin(dlng/2)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
distance := R * c distance := R * c