From 0ff1b76450d01cddbca352b7bf9ec3bce3224ad9 Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Thu, 22 Mar 2018 12:52:22 +0100 Subject: [PATCH] routeguide: reimplement distance calculation --- examples/route_guide/server/server.go | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/examples/route_guide/server/server.go b/examples/route_guide/server/server.go index cb452d21..ececfa7e 100644 --- a/examples/route_guide/server/server.go +++ b/examples/route_guide/server/server.go @@ -167,22 +167,20 @@ func toRadians(num float64) float64 { } // 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 { const CordFactor float64 = 1e7 - const R float64 = float64(6371000) // metres - lat1 := float64(p1.Latitude) / CordFactor - lat2 := float64(p2.Latitude) / CordFactor - lng1 := float64(p1.Longitude) / CordFactor - lng2 := float64(p2.Longitude) / CordFactor - φ1 := toRadians(lat1) - φ2 := toRadians(lat2) - Δφ := toRadians(lat2 - lat1) - Δλ := toRadians(lng2 - lng1) + const R float64 = float64(6371000) // earth radius in metres + lat1 := toRadians(float64(p1.Latitude) / CordFactor) + lat2 := toRadians(float64(p2.Latitude) / CordFactor) + lng1 := toRadians(float64(p1.Longitude) / CordFactor) + lng2 := toRadians(float64(p2.Longitude) / CordFactor) + dlat := lat2 - lat1 + dlng := lng2 - lng1 - a := math.Sin(Δφ/2)*math.Sin(Δφ/2) + - math.Cos(φ1)*math.Cos(φ2)* - math.Sin(Δλ/2)*math.Sin(Δλ/2) + a := math.Sin(dlat/2)*math.Sin(dlat/2) + + math.Cos(lat1)*math.Cos(lat2)* + math.Sin(dlng/2)*math.Sin(dlng/2) c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) distance := R * c