The data file stores several cities, in each city from 3 to 10 points with their coordinates.

To determine the city by user coordinates github.com/kellydunn/golang-geo is used. Based on the determined city, we load the coordinates of points for the desired city. How can I find the one closest to the user in Golang without using mongodb?

  • It's not very clear who makes you use MongoDB so hard. The question to her is still not directly related. - D-side
  • @ D-side anticipating links, such as icchan.imtqy.com/2014/10/18/… decided to immediately stipulate the use of mongodb with its geocoding - OstaninKI
  • Yes, do not worry, there are such people who may be mistaken for me (who happened to work on products in which Mongu was dragged in exclusively for geocoding; apparently, not knowing that there are a lot of other solutions). Besides, golang-geo doesn't support Mongu anyway. - D-side

1 answer 1

https://gist.github.com/cdipaolo/d3f8db3848278b49db68

The code for getting the distance In my case, I use it to sort the points and give the next few

// haversin(θ) function func hsin(theta float64) float64 { return math.Pow(math.Sin(theta/2), 2) } // Distance function returns the distance (in meters) 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 // // distance returned is METERS!!!!!! // http://en.wikipedia.org/wiki/Haversine_formula func Distance(lat1, lon1, lat2, lon2 float64) float64 { // convert to radians // must cast radius as float to multiply later var la1, lo1, la2, lo2, r float64 la1 = lat1 * math.Pi / 180 lo1 = lon1 * math.Pi / 180 la2 = lat2 * math.Pi / 180 lo2 = lon2 * math.Pi / 180 r = 6378100 // Earth radius in METERS // calculate h := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1) return 2 * r * math.Asin(math.Sqrt(h)) }