使用SQL在一个纬度/经度坐标和一个固定坐标之间的近似距离

时间:2015-10-26 14:04:01

标签: mysql sql coordinates latitude-longitude

下面

Distance between two lat,lon points

我找到了一个非常简单和好的公式:

d = sqrt(pow(lat2-lat1, 2) + cos(lat1)*pow(lon2-lon1, 2))
我正在使用的

SELECT name, SQRT(POW(lat-45, 2) + COS(45)*POW(lon-8, 2)) AS distance
FROM shop
ORDER BY distance

并且一切正常,因为我只需要获得近似的RELATIVE距离。

然后我需要一个绝对距离,即使近似...我开始意识到也许“d”不能以米/英里换算,因为例如有180度的纬度但经度为360度,所以这个几乎是毕达哥拉斯定理以一种可能的绝对计算方式“拉伸”对角线......过了一会儿,我放弃了......这里我上午。

如何将“d”转换为以米/英里为单位的绝对距离?

PS:是的,我会在最终版本中预先计算SQL查询中的所有常量......

2 个答案:

答案 0 :(得分:0)

在SQL中获取metters的距离检查此查询,您也可以将其转换为函数

declare @lat1 FLOAT
declare @lat2 FLOAT
declare @lon1 FLOAT
declare @lon2 FLOAT

SET @lat1 = 18.4768047
SET @lon1 = -69.9516518
SET @lat2 = 18.4624464
SET @lon2 = -69.9652686


select (ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371)*1000

这是一个例子

UPDATE !!!

我为MySQL创建了这个程序,用于获取KM,Miles,Metters和码

DELIMITER //
CREATE PROCEDURE sp_Distance(lat1 FLOAT,lon1 FLOAT,lat2 FLOAT,lon2 FLOAT,unit INT) 
BEGIN  

declare KM INT;
declare MILE INT;
declare METTER INT;
declare YARD INT;

SET KM = 6371;
SET MILE = 3959;
SET METTER = KM*1000;
SET YARD = MILE*1760;


SELECT ((ACOS(SIN(PI()*lat1/180.0)*SIN(PI()*lat2/180.0)+
COS(PI()*lat1/180.0)*COS(PI()*lat2/180.0)*COS(PI()*lon2/180.0-PI()*lon1/180.0)))*
(SELECT CASE
WHEN unit = 1 THEN KM
WHEN unit = 2 THEN MILE
WHEN unit = 3 THEN METTER
WHEN unit = 4 THEN YARD END as unit_value)
) as Distance;
END;//

DELIMITER ;

致电:

call sp_Distance(18.4768047,-69.9516518,18.4624464,-69.9652686,1)

对于SQL

CREATE PROCEDURE sp_Distance(@lat1 FLOAT,@lon1 FLOAT,@lat2 FLOAT,@lon2 FLOAT,@unit INT) 
AS
BEGIN 

declare @KM INT
declare @MILE INT
declare @METTER INT
declare @YARD INT

SET @KM = 6371
SET @MILE = 3959
SET @METTER = @KM*1000
SET @YARD = @MILE*1760

SELECT ((ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+
COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0)))*
(SELECT CASE
WHEN @unit = 1 THEN @KM
WHEN @unit = 2 THEN @MILE
WHEN @unit = 3 THEN @METTER
WHEN @unit = 4 THEN @YARD END as unit_value)
) as Distance
END

致电:

exec sp_Distance 18.4768047,-69.9516518,18.4624464,-69.9652686,1

答案 1 :(得分:0)

这对我有用:

$ sql =" SELECT *,(((acos(sin(("。$ latitude。" * pi()/ 180))* sin((Latitude * pi()/ 180))+ cos(("。$ latitude。" * pi()/ 180))* cos((Latitude * pi()/ 180))* cos(("。$ longitude。" - Longitude)* pi()/ 180))))* 180 / pi())* 60 * 1.1515 * 1.609344)作为距离 从商店到哪里距离> ="。$ distance; //距离以公里为单位

还可以看看谷歌地图功能: https://developers.google.com/maps/articles/phpsqlsearch_v3?csw=1#findnearsql