MySQL select coordinates within range

后端 未结 5 1676
有刺的猬
有刺的猬 2020-11-28 12:38

I\'ve in my database 100 000 addresses (that is records).

Each one of them has its own coordinates (latitude and longitude).

Now, given the geo location of

5条回答
  •  执念已碎
    2020-11-28 13:01

    You can use what is called the Haversine formula.

    $sql = "SELECT *, ( 3959 * acos( cos( radians(" . $lat . ") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $lng . ") ) + sin( radians(" . $lat . ") ) * sin( radians( lat ) ) ) ) AS distance FROM your_table HAVING distance < 5";
    

    Where $lat and $lng are the coordinates of your point, and lat/lng are your table columns. The above will list the locations within a 5 nm range. Replace 3959 by 6371 to change to kilometers.

    This link could be useful: https://developers.google.com/maps/articles/phpsqlsearch_v3

    Edit: I didn't see you mentioned Java. This example is in PHP but the query is still what you need.

提交回复
热议问题