'Is current location within radius of items stored in a table?
I have a table that stores longitude / latitude / radius ( miles ) per row. What I am trying to figure out is how to select ONLY the rows that my current point is within.
This is the opposite of querying locations within a given radius of my current location, instead, I actually want to query locations that my current point is within.
Any help here would be greatly appreciated.
Solution 1:[1]
This is easily a math problem. The distance between 2 points (x1, y1)
and (x2, y2)
can be calculated as follows:
Simple Pythagoras. Query your database, point one is the point you want to find, point two is the one you get from the database, if the result of the above statement is smaller then the radius, it's in your range. (assuming all units match. You'll probably want to convert the lat/lon difference to km/whatever unit your radius is)
Solution 2:[2]
Note that if you want to have an accurate radius calculation for good ol' earth latitudes/longitudes, you'd have to use more complicated functions than the simple pythagorean distance mentioned in the accepted answer; look for "great circle distance", as e.g. posted in another thread already; however, for your purposes, the pythagorean distance should be close enough I guess; it delivers a reasonably good approximation, except if your latitude/longitude positions are somewhere near the poles.
And, just for completeness, your problem is actually not the opposite to the question "What locations are in a certain radius around my location?" - it's the exact same, only from the other direction - but since distance calculations are symmetric, it actually doesn't matter which direction you check!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Community |