我從谷歌地圖反向地理編碼API獲得緯度和經度,然後我需要的是這樣的:如何用MySQL的Haversine公式測量距離?
mysql_query("SELECT users.*, ".mysql_distance_column($lat,$lng)." FROM users ORDER BY DISTANCE";
function mysql_distance_column($lat=40 , $lng=-73) {
$defaultLatitudeColumn = 'user_lat';
$defaultLongitudeColumn='user_lng';
$defaultColumnName='user_distance';
return "((
(3956 * 2 * ASIN(SQRT(POWER(SIN(({$lat} - abs({$defaultLatitudeColumn}))
* pi()/180/2), 2) + COS({$lat} * pi()/180)
* COS(abs({$defaultLatitudeColumn}) * pi()/180)
* POWER(SIN(({$lng} - {$defaultLongitudeColumn}) * pi()/180/2), 2)))
))) as {$defaultColumnName} ";
}
UPDATE 我不能GE這個工作
delimiter //
CREATE FUNCTION `GeoDistMiles`(lat1 FLOAT (10,6), lon1 FLOAT (10,6), lat2 FLOAT (10,6), lon2 FLOAT (10,6))
RETURNS FLOAT
DETERMINISTIC
NO SQL
BEGIN
DECLARE pi, q1, q2, q3 FLOAT (10,6);
DECLARE rads FLOAT (10,6) DEFAULT 0;
SET pi = PI();
SET lat1 = lat1 * pi/180;
SET lon1 = lon1 * pi/180;
SET lat2 = lat2 * pi/180;
SET lon2 = lon2 * pi/180;
SET q1 = COS(lon1-lon2);
SET q2 = COS(lat1-lat2);
SET q3 = COS(lat1+lat2);
SET rads = ACOS(0.5*((1.0+q1)*q2 - (1.0-q1)*q3));
RETURN 3963.346 * rads;
END
你的計算有多遠?他們是走了還是稍微離開一點? – anon 2011-02-02 18:39:45