Function that calculates the distance between two coordinates

I just do a web application that uses google maps api v3.
And application requirements should calculate the distance between two coordinates given.

The first, we need 2 coordinates. Of course, right?

I used :

and

http://maps.google.com/maps/api/js

Lock like that:

Get current coordinates by code:

GMaps.geolocate({
 success: function(position) {
 var latlat = position.coords.latitude;
 var longlong = position.coords.longitude;
 var position = latlat + “,” + longlong;
 document.write(position);
 },
 error: function(error) {
 alert(‘Lấy vị trí hiện tại thật bại: ‘+error.message);
 },
 not_supported: function() {
 alert(“Trình duyệt của bạn không hỗ trợ định vị Google Maps”);
 }
 });

Result:

get current coordinates

Now I take a coordinate any, maybe: 21.025346,105.827571

Do you know Haversine formula, read more

// In ra khoảng cách KM
 function HaversineInKM(lat1, long1, lat2, long2)
 {
 var dlong = (long2 — long1) * _d2r;
 var dlat = (lat2 — lat1) * _d2r;
 var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
 var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 — a));
 var d = _eQuatorialEarthRadius * c;
 return d;
 }

Now, you can calculate the distance between two coordinates with my code.

With PHP you can using:

public static function HaversineInKM($position_1, $position_2){
 $_eQuatorialEarthRadius = 6378.1370;
 $_d2r = (pi() / 180.0);
 $lat1 = explode(‘,’, $position_1)[0];
 $long1 = explode(‘,’, $position_1)[1];
 $lat2 = explode(‘,’, $position_2)[0];
 $long2 = explode(‘,’, $position_2)[1];
 $dlong = ($long2 — $long1) * $_d2r;
 $dlat = ($lat2 — $lat1) * $_d2r;
 $a = pow(sin($dlat / 2.0), 2.0) + cos($lat1 * $_d2r) * cos($lat2 * $_d2r) * pow(sin($dlong / 2.0), 2.0);
 $c = 2.0 * atan2(sqrt($a), sqrt(1.0 — $a));
 $d = $_eQuatorialEarthRadius * $c;
 return $d;
}

GOOD LUCK!