So, ideally you save the latitude and longitude of the locations that will be saved in the bank. Then, to calculate the distance between two points there are several formulas.
In this link there are some formulas that you can use: https://www.movable-type.co.uk/scripts/latlong.html
I’ve been using the Spherical law of cosines. Follows the function I use, in php.
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
Receiving as input, the latitude and longitude of each point and a char "N" to indicate that the return is in miles or "K" to indicate that the return is in meters.
If you are working with many sites, I advise you to search for a more efficient way to store locations, so you don’t have to go through all the points in the bank. Something like, nearby cities or even nearby states.
I’ll have to save the coordinates in the database to make the comparisons with that function there, right? I’ll test and return with the results.
– Alisson Maciel
Now explain to me how I use?
– Alisson Maciel
So, if you have the positions, just enter with the latitude and longitude of the user and with the latitude and longitude of one of the locations of the bank, the last variable the $Unit, you enter with the letter "K", the return will be the distance between the user and the chosen location.
– Diego Cacau