Hi I have the need to calculate the distance between two points having the lat and long.
I would like to avoid any call to external API.
I tried to implement the Haversine Formula in PHP:
Here is the code:
class CoordDistance
{
public $lat_a = 0;
public $lon_a = 0;
public $lat_b = 0;
public $lon_b = 0;
public $measure_unit = 'kilometers';
public $measure_state = false;
public $measure = 0;
public $error = '';
public function DistAB()
{
$delta_lat = $this->lat_b - $this->lat_a ;
$delta_lon = $this->lon_b - $this->lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$this->measure = $distance;
}
}
Testing it with some given points which have public distances I don't get a reliable result.
I don't understand if there is an error in the original formula or in my implementation
Try this function out to calculate distance between to points of latitude and longitude
Then use the fucntion as
Hope it helps
Not long ago I wrote an example of the haversine formula, and published it on my website:
➽ Note that you get the distance back in the same unit as you pass in with the parameter
$earthRadius
. The default value is 6371000 meters so the result will be in [m] too. To get the result in miles, you could e.g. pass 3959 miles as$earthRadius
and the result would be in [mi]. In my opinion it is a good habit to stick with the SI units, if there is no particular reason to do otherwise.Edit:
As TreyA correctly pointed out, the Haversine formula has weaknesses with antipodal points because of rounding errors (though it is stable for small distances). To get around them, you could use the Vincenty formula instead.
For exact values do it like that:
Hmm I think that should do it...
Edit:
For formulars and at least JS-implementations try: http://www.movable-type.co.uk/scripts/latlong.html
Dare me... I forgot to deg2rad all the values in the circle-functions...
Here the simple and perfect code for calculating the distance between two latitude and longitude. The following code have been found from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/
For the ones who like shorter and faster(not calling deg2rad()).