mySQL longitude and latitude query for other rows within x mile radius

后端 未结 1 2069
滥情空心
滥情空心 2020-11-29 19:24

I have a database populated with roughly 10k rows currently. All of them have a longitude/latitude based on the center of a zipcode. I found a query that I am now attempting

相关标签:
1条回答
  • 2020-11-29 20:09

    Here is the query I use on the store locator I work with:

    SELECT
        `id`,
        (
            6371 *
            acos(
                cos( radians( :lat ) ) *
                cos( radians( `lat` ) ) *
                cos(
                    radians( `long` ) - radians( :long )
                ) +
                sin(radians(:lat)) *
                sin(radians(`lat`))
            )
        ) `distance`
    FROM
        `location`
    HAVING
        `distance` < :distance
    ORDER BY
        `distance`
    LIMIT
        25
    

    :lat and :long are the points the passed by the user where lat and long are the points stored in the database.

    The :distance is measured in miles, in the working version of the code the :distance is actually pulled from a drop down ranging from 10-50 miles

    Changing the code to work with kilometers can be accomplished by changing 3959 (the distance from the center of the earth to its surface in miles) to 6371 (3959 miles converted to kilometers) thanks to joshhendo for that solution.

    0 讨论(0)
提交回复
热议问题