Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search nearby places stored in my database?

I'm developing a web app where the user sets a place in a map (Google Maps API) and I store the coordinates in a database.

At another page, I want to do a search which consists in getting my local coordinates and retrieve nearby places previously stored at my database based on a radius.

How can I do this?

like image 266
Everton Mendonça Avatar asked Mar 10 '15 20:03

Everton Mendonça


2 Answers

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.

like image 162
MrUpsidown Avatar answered Oct 25 '22 09:10

MrUpsidown


sounds like a "store locator script", for which google has an intro to here:

https://developers.google.com/maps/articles/phpsqlsearch_v3

what you'll need to do is to create a backend which allows your user to enter each place into the database. It's quite a large task and if I were you, I would take an open source script or similar and adapt it to your needs.

for example:

https://github.com/bjorn2404/jQuery-Store-Locator-Plugin

I would do a search for "free store locator script" and try their demos, see what appeals to you the most.

like image 32
luke_mclachlan Avatar answered Oct 25 '22 09:10

luke_mclachlan