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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With