Last Updated: February 25, 2016
·
7.594K
· neeph

# Calculate distance between two coordinates in PHP, JavaScript and MySQL

All returns the distance in kilometers, assuming a earth radius of 6371 km.

## PHP

``````function calculateDistance(\$ini, \$fin) {
\$R = 6371; // km
\$a = sin(\$dLat/2) * sin(\$dLat/2) + cos(deg2rad(\$ini[0])) * cos(deg2rad(\$fin[0])) * sin(\$dLon/2) * sin(\$dLon/2);
\$c = 2 * atan2(sqrt(\$a), sqrt(1-\$a));
\$d = \$R * \$c;
return \$d;
}``````

## JavaScript

``````var calculateDistance = function(lat1, lon1, lat2, lon2) {
var R = 6371; // km

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}``````

## MySQL

``````CREATE FUNCTION `calc_distance` (lat1 DECIMAL(10,6), long1 DECIMAL(10,6), lat2 DECIMAL(10,6), long2 DECIMAL(10,6))
RETURNS DECIMAL(10,6)
RETURN (6353 * 2 * ASIN(SQRT( POWER(SIN((lat1 - abs(lat2)) * pi()/180 / 2),2) + COS(lat1 * pi()/180 ) * COS( abs(lat2) *  pi()/180) * POWER(SIN((long1 - long2) *  pi()/180 / 2), 2) )))``````

339.9K
19

### Pretty print array php

268.3K
0

241.4K
10

#### Have a fresh tip? Share with Coderwall community!

Best #Php Authors
brandonbeeks
339.6K
jvinceso
267.7K
hnordt
241.3K
rmcdaniel
237.6K
Awesome Job