Reputation: 45
Im working on maps, in which I need to show nearest locations from the user GEO coordinates. These nearest location should be within 1km or user specified radius.
Instead of running a query and calculating the distance for all geo coordinates in my DB, I have narrow down my selection by choosing country - state - city. However I still dont find this way is more efficient.
Could someone suggest me the better way to solve this issue.
Upvotes: 0
Views: 872
Reputation: 7846
I suggest you work out max and min latitude and max and min longitude so that all points that have both latitude and longitude between the respective min and max lie in the 2km x 2km square which is centered on the current point. Then you can just run a query to select which geopoints are closest. To do that, you need to work out what the ratio is between a km and a degree of latitude, and the ratio between a km and a degree of longitude. The answer is
1 degree of latitude = 6371000 * Math.PI / 180 metres
1 degree of longitude = Cos(Latitude) * 6371000 * Math.PI / 180 metres
because 6371000 is average earth radius in metres. Some points (i.e. at the corners of the square) will be more than 1km away, however you could then work out exact distance of each point within that square if the answer needs to be accurate. NB: a lot of Cosine functions take radians rather than degrees, so make sure to get the units right!
Upvotes: 0
Reputation: 612
What you are looking for is the Haversine Formula, based on co-ordinates. You will have to compare the distance between co-ordinates of the location and the points of interest using Haversine. Then if the result is below the threshold (1km) you display the point of interest.
Upvotes: 1
Reputation: 1839
See this Wikipedia article if you need a quick and fairly accurate estimation of distance using coordinates.
Upvotes: 1