总体目标:找到给定拉链30英里内的所有邮政编码.
数据来源:邮政编码列表,纬度和经度为“x”和“ ‘Y’.
例:
create or replace view zips as
select 37171 zip, 36.362704 y, -87.30434 x,'Southside' City, 'TN' State from dual
union
select 37212, 36.133012, -86.802764, 'Nashville', 'TN' from dual
union
select 37027, 36.00245, -86.791159, 'Brentwood', 'TN' from dual
union
select 37191, 36.501196, -87.539057, 'Woodlawn', 'TN' from dual
union
select 37067, 35.928406, -86.805538, 'Franklin', 'TN' from dual ;
我尝试了什么:我发现了一些看起来像solve all my problems的东西:
CREATE OR REPLACE FUNCTION distance (Lat1 IN NUMBER,
Lon1 IN NUMBER,
Lat2 IN NUMBER,
Lon2 IN NUMBER,
Radius IN NUMBER DEFAULT 3963) RETURN NUMBER IS
-- Convert degrees to radians
DegToRad NUMBER := 57.29577951;
BEGIN
RETURN(NVL(Radius,0) * ACOS((sin(NVL(Lat1,0) / DegToRad) * SIN(NVL(Lat2,0) / DegToRad)) +
(COS(NVL(Lat1,0) / DegToRad) * COS(NVL(Lat2,0) / DegToRad) *
COS(NVL(Lon2,0) / DegToRad - NVL(Lon1,0)/ DegToRad))));
END;
然而,它给了我时髦的数字 – 一直太小(我知道从富兰克林到纳什维尔不是1英里),但不是我能确定的一个恒定因素. (我以前测试的代码如下 – 我只是将Google地图上的距离与这些距离进行比较)
select b.zip
,b.city
,b.state
,distance(a.x,a.y,b.x,b.y) distance
from zips a, zips b
where a.zip=37067
order by distance;
所以,我想也许地理数据集团有一种不同的方式记录lat&很久,我找到了Wikipedia’s Haversine formula并将其变成了一个功能
CREATE OR REPLACE FUNCTION distance (Lat1_d IN NUMBER,
Lon1_d IN NUMBER,
Lat2_d IN NUMBER,
Lon2_d IN NUMBER,
Radius IN NUMBER DEFAULT 3959) RETURN NUMBER IS
-- Convert degrees to radians
DegToRad NUMBER := .0174532925;
Lat1 NUMBER := Lat1_d * DegToRad;
Lon1 NUMBER := Lon1_d * DegToRad;
Lat2 NUMBER := Lat2_d * DegToRad;
Lon2 NUMBER := Lon2_d * DegToRad;
BEGIN
RETURN 2*Radius *
asin(
sqrt(
power(sin((Lat2-Lat1)/2),2) + cos(Lat1) * cos(Lat2) * power(sin((Lon2-Lon1)/2),2)
)
)
;
END;
同样的问题 – 结果几乎完全相同,这让我想知道问题是什么.我不做什么转变?我错过了什么?
请注意,我很乐意假设一个平坦的地球并使用毕达哥拉斯距离,因为我只会看到我看到的每组邮政编码30-50英里,但我需要弄清楚我的纬度是什么/经度转换也出错了.
最佳答案 看起来像一个参数问题.标题是:
CREATE OR REPLACE FUNCTION distance (Lat1 IN NUMBER,
Lon1 IN NUMBER,
Lat2 IN NUMBER,
Lon2 IN NUMBER,
而你的称呼如下:
distance(a.x,a.y,b.x,b.y)
但你的观点是:
create or replace view zips as
select 37171 zip, 36.362704 y, -87.30434 x,'Southside' City, 'TN' State from dual
union
select 37212, 36.133012, -86.802764, 'Nashville', 'TN' from dual
union
select 37027, 36.00245, -86.791159, 'Brentwood', 'TN' from dual
union
select 37191, 36.501196, -87.539057, 'Woodlawn', 'TN' from dual
union
select 37067, 35.928406, -86.805538, 'Franklin', 'TN' from dual ;
根据该视图,x是经度,y是纬度.所以函数调用应该是:
distance(a.y,a.x,b.y,b.x)
或者,您可以在视图中交换“x”和“y”别名,并保留其他所有内容.