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
Hello here Code For Get Distance and Time Using Two Different Lat and Long
You can check Example Below Link get time between two different locations using latitude and longitude in php
It's just addition to @martinstoeckli and @Janith Chinthana answers. For those who curious about which algorithm is fastest i wrote the performance test. Best performance result shows optimized function from codexworld.com:
Here is test results:
Quite old question, but for those interested in a PHP code that returns the same results as Google Maps, the following does the job:
I've tested with various coordinates and it works perfectly.
I think it should be faster then some alternatives too. But didn't tested that.
Hint: Google Maps uses 6378137 as Earth radius. So using it with other algorithms might work as well.
I found this code which is giving me reliable results.
results :
The multiplier is changed at every coordinate because of the great circle distance theory as written here :
http://en.wikipedia.org/wiki/Great-circle_distance
and you can calculate the nearest value using this formula described here:
http://en.wikipedia.org/wiki/Great-circle_distance#Worked_example
the key is converting each degree - minute - second value to all degree value:
Try this gives awesome results