Last active
May 1, 2021 06:39
-
-
Save iamdejan/5e6320d9befd298c4848cecd409567dc to your computer and use it in GitHub Desktop.
Haversine Distance calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "math" | |
| ) | |
| const earthRadiusKM = 6371.0 | |
| type Location struct { | |
| Latitude float64 | |
| Longitude float64 | |
| } | |
| func degreeToRadians(angle float64) float64 { | |
| return angle * (math.Pi / 180.0) | |
| } | |
| func NewLocation(lat_degree float64, long_degree float64) Location { | |
| return Location{ | |
| Latitude: degreeToRadians(lat_degree), | |
| Longitude: degreeToRadians(long_degree), | |
| } | |
| } | |
| func hav_function(angle_rad float64) float64 { | |
| return (1 - math.Cos(angle_rad)) / 2.0 | |
| } | |
| func hav_formula(first_city Location, second_city Location) float64 { | |
| // first, find the difference between latitudes and longitudes | |
| var latitude_diff float64 = first_city.Latitude - second_city.Latitude | |
| var longitude_diff float64 = first_city.Longitude - second_city.Longitude | |
| // then, compute the haversine of those variables | |
| var hav_latitude float64 = hav_function(latitude_diff) | |
| var hav_longitude float64 = hav_function(longitude_diff) | |
| // last, put the results into formula | |
| return hav_latitude + math.Cos(first_city.Latitude)*math.Cos(second_city.Latitude)*hav_longitude | |
| } | |
| func archaversine(hav_angle float64) float64 { | |
| var sqrt_hav_angle float64 = math.Sqrt(hav_angle) | |
| return 2.0 * math.Asin(sqrt_hav_angle) | |
| } | |
| func haversine_distance(first_city Location, second_city Location) float64 { | |
| var hav_central_angle float64 = hav_formula(first_city, second_city) | |
| var central_angle_rad float64 = archaversine(hav_central_angle) | |
| return earthRadiusKM * central_angle_rad | |
| } | |
| func main() { | |
| var lat float64 | |
| var long float64 | |
| fmt.Scanf("%f %f", &lat, &long) | |
| var first_city = NewLocation(lat, long) | |
| fmt.Scanf("%f %f", &lat, &long) | |
| var second_city = NewLocation(lat, long) | |
| fmt.Printf("distance between 2 cities = %f km\n", haversine_distance(first_city, second_city)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment