Reputation: 3849
I am building a database of local spots, each of these local spots is stored in my mysql database with a latitude and longitude coordinate set.
I want to build a search where a user enters his location into a form, my form will determine the users latitude and longitude via the google maps geolocation API successfully.
My problem/question is this. How can I determine which sets of latitude and longitude of the items in my mysql database would be within a predined radius (say 25miles).
Is there a way to calculate the outerbounds of latitude and longitude frm the 25 mile radius and then check for items that match that # with a basic mysql select? If so what would the converion between miles and lat/long degrees? If not, is there any other way to pull this off anyone could think of?
Thank you!!
Upvotes: 2
Views: 2547
Reputation: 470
Almost the same as what @Skidrow wrote before but in php. Php could be better if you want to check the result you already loaded else you have to iterate all the post in mysql. If that case the mysql version would be better
function calculateDistance($targetLat, $targetLng, $againstLat, $againstLng, $units = 'miles')
{
$result = 3958.75 * acos(
sin($targetLat / 57.2958) * sin($againstLat / 57.2958) +
cos($targetLat / 57.2958) * cos($againstLat / 57.2958) *
cos($againstLng / 57.2958 - $targetLng / 57.2958)
);
switch ($units)
{
default:
case "":
case "miles":
$result *= 1;
break;
}
return $result;
}
Test using this function
$target* = the spot in your database
$against* = user location
Upvotes: 2
Reputation: 12592
There are many ways. You can use a spatial index or the harvesine formula. You can also create a proximity search. Read here: https://developers.google.com/maps/articles/geospatial. The harvesine formula is the great circle distance between two points on a sphere.
Upvotes: 1