I've been making search functionality that takes in two fields, Start Postcode and End Postcode. The search is supposed to query the database and collect any records that fall into the radius for both postcodes. I can retrieve the records but after, I need to get the distance between the postcodes. I know how to use the GMaps API to do this but I need to do it locally with PHP for performance reasons (Looping over multiple records etc). It would be very bad for performance to do this with an API. Any suggestions?
Just to be clear: I need a code solution to calculate distance between two postcodes without API use. Is this possible and if so how?
PHP is preferred but even just the logical idea represented in any language is okay for me.
If you have latitude and longtitude you can calculate the distance between two points without api just using this code:
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;
}
}
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";
Store the Lat Lon when you save the record and then work it out from that. It does mean a call to Google Maps API on save though.