SQlite Getting nearest locations (with latitude and longitude)

后端 未结 5 660
無奈伤痛
無奈伤痛 2020-11-22 05:54

I have data with latitude and longitude stored in my SQLite database, and I want to get the nearest locations to the parameters I put in (ex. My current location - lat/lng,

5条回答
  •  天涯浪人
    2020-11-22 06:51

    I know this has been answered and accepted but thought I'd add my experiences and solution.

    Whilst I was happy to do a haversine function on the device to calculate the accurate distance between the user's current position and any particular target location there was a need to sort and limit the query results in order of distance.

    The less than satisfactory solution is to return the lot and sort and filter after the fact but this would result in a second cursor and many unnecessary results being returned and discarded.

    My preferred solution was to pass in a sort order of the squared delta values of the long and lats:

    (( - LAT_COLUMN) * ( - LAT_COLUMN) +
     ( - LNG_COLUMN) * ( - LNG_COLUMN))
    

    There's no need to do the full haversine just for a sort order and there's no need to square root the results therefore SQLite can handle the calculation.

    EDIT:

    This answer is still receiving love. It works fine in most cases but if you need a little more accuracy, please check out the answer by @Teasel below which adds a "fudge" factor that fixes inaccuracies that increase as the latitude approaches 90.

提交回复
热议问题