下面这个函数(PHP实现)用于计算两个地理坐标之间的距离,主要用于处理源自Google地图的坐标数据。

验证数据:[48.856667, 2.350987], [38.895113, -77.036366]
验证结果:6172.4281776242KM

/**
 * Calculate the distance between two coordinates.
 * @param array $s, array(float:latitude, float: longitude)
 * @param array $e, array(float:latitude, float: longitude)
 * @return float, the distance
 */
function geo_distance($s, $e) {
	
	//earth's mean radius in KM
	$r = 6378.137;
	
	$s[0] = deg2rad($s[0]);
	$s[1] = deg2rad($s[1]);
	
	$e[0] = deg2rad($e[0]);
	$e[1] = deg2rad($e[1]);
	
	$d0 = abs($s[0] - $e[0]);
	$d1 = abs($s[1] - $e[1]);
	
	$p = pow(sin($d0/2), 2) + cos($s[0]) * cos($e[0]) * pow(sin($d1/2), 2);
	
	$ds = $r * 2 * asin(sqrt($p));
	
	return $ds;
}

MySQL Function

DELIMITER //
CREATE FUNCTION geo_distance(lat1 FLOAT, lng1 FLOAT, lat2 FLOAT, lng2 FLOAT) RETURNS FLOAT
BEGIN
	
	DECLARE r INT DEFAULT 6378137;
	DECLARE s0 FLOAT;
	DECLARE s1 FLOAT;
	DECLARE e0 FLOAT;
	DECLARE e1 FLOAT;
	
	DECLARE d0 FLOAT;
	DECLARE d1 FLOAT;
	
	SET s0 = RADIANS(lat1);
	SET s1 = RADIANS(lng1);
	SET e0 = RADIANS(lat2);
	SET e1 = RADIANS(lng2);
	
	SET d0 = ABS(s0 - e0);
	SET d1 = ABS(s1 - e1);
	
	RETURN r * 2 * ASIN(SQRT(POW(SIN(d0/2),2) + COS(s0)*COS(e0)*POW(SIN(d1/2),2)));

END//

DELIMITER ;