Need help with finding nearby location
I am working app which need to find nearby distributors of particular product. As of now I have current locations latitude and longitude. Besides that I also have list of all product distributors with their respective coordinates. I am running query which gives me nearest 10 locations but for that it goes thorough every record in DB calculate distance between current and that particular location. It takes way too much time.开发者_运维百科 Is there any other alternative that can I take ?
Can you not first narrow down the data set by creating a max and min long and lat (say within 10 miles of the current location). You can then query the data set by lat > minLat and lat < maxLax, etc. You could then sort them as you are proposing by calculating the actual distances on the reduced subset if you need too.
To avoid calculating distance on every location you could create a lat long box (lets say for 10 miles) using the max top left lat long (10 miles up and 10 miles left) and the max bottom right lat long (10 miles down and 10 miles right). Then your query will find lat longs in that box using >= and <= and then calculate the distance for each of those to filter out the locations in the corners which exceed 10 miles.
Another other option is to look into spatial indexing for SQLite.
You can narrow down list of location by creating rectangular buffer around your location, to filter locations that are nearby.
SELECT * FROM table t WHERE t.lat<(lat+buff) AND t.long<(long+buff) AND t.lat>(lat-buff) AND t.long>(long-buff)
lat, long - your location, buff - some value you can adjust to match your app need (e.g. 100 feet, 1 mile, etc)
Then you can ran your distance calculation on returned records.
精彩评论