2012-03-22 141 views
0

我使用html5地理位置API来获取我在经度和纬度的位置。我想将它们存储在一个位置表中,并希望在特定距离内检索这些位置。使用db2查找特定距离内的位置

我目前的经度和纬度都存储在变量“latval”,“longval”,“距离” 我的表是“位置” 列是“位置”,“纬度”,“长” 我使用DB2 Express C作为数据库,经纬度列现在设置为双重类型。我应该使用什么类型来存储这些值,以及在距离内获取位置名称的查询是什么 谢谢。

回答

1

它看起来像Express C的扩展包括空间处理。我从来没有使用它(目前似乎无法访问),所以我无法对它说话。我假设你想使用它(查找半径内的所有位置都是非常标准的查询)。

如果由于某种原因,你不能使用扩展,这里就是我会做:
保持你的表原样,或者可能使用浮点数据类型,但是请使用完整的属性名(没有理由截断它们)。对于简单的需求,'位置'的名称可以存储在表中,但如果不止一个事物在同一位置(因此实际点只存在一次),您可能想给它一个数字ID。
你也需要覆盖纬度和经度的标记(可能每个方向一个,或者每个方向一个)。

然后,给定一个起始位置和距离,使用此查询:

SELECT name, latitude, longitude 
FROM location 
WHERE (latitude >= :currentLatitude - :distance 
     AND latitude <= :currentLatitude + :distance) 
AND (longitude >= :currentLongitude - :distance 
    AND longitude <= :currentLongitude + :distance) 
    -- The previous four lines reduce the points selected to a box. 
    -- This is, or course, not completely correct, but should allow 
    -- the query to use the indicies to greatly reduce the initial 
    -- set of points evaluated. 
    -- You may wish to flip the condition and use ABS(), but 
    -- I don't think that would use the index... 
AND POWER(latitude - :currentLatitude, 2) + POWER(longitude - :currentLongitude, 2) 
     <= POWER (:distance, 2) 
    -- This uses the pythagorean theorem to find all points within the specified 
    -- distance. This works best if the points have been pre-limited in some 
    -- way, because an index would almost certainly not be used otherwise. 
    -- Note that, on a spherical surface, this isn't completely accurate 
    -- - namely, distances between longitude points get shorter the farther 
    --  from the equator the latitude is - 
    -- but for your purposes is likely to be fine. 


编辑:

发现this after searching for 2 seconds on google,这也提醒了我,:distance将是错误的单位。修订后的查询是:

WITH Nearby (name, latitude, longitude, dist) as (
SELECT name, latitdude, longitude, 
     ACOS(SIN(RADIANS(latitude)) * SIN(RADIANS(:currentLatitude)) + 
      COS(RADIANS(latitude)) * COS(RADIANS(:currentLatitude)) * 
      COS(RADIANS(:currentLongitude - longitude))) * :RADIUS_OF_EARTH as dist 
FROM location 
WHERE (latitude >= :currentLatitude - DEGREES(:distance/:RADIUS_OF_EARTH) 
     AND latitude <= :currentLatitude + DEGREES(:distance/:RADIUS_OF_EARTH)) 
AND (longitude >= :currentLongitude - 
       DEGREES(:distance/:RADIUS_OF_EARTH/COS(RADIANS(:currentLatitude))) 
    AND longitude <= :currentLongitude + 
       DEGREES(:distance/:RADIUS_OF_EARTH/COS(RADIANS(:currentLatitude)))) 
) 
SELECT * 
FROM Nearby 
WHERE dist <= :distance 

请注意,包裹在一个UDF的距离函数标DETERMINISTIC将允许它被放置在两个SELECTHAVING部分,但实际上只被称为一次,省去了为CTE。

+0

感谢您的努力。我正在寻找使用球形公式的距离查询。什么是使用大圆距公式的查询? – 2012-03-23 04:40:23

+0

非常感谢你的x-zero。我现在在我的大学里。我回家后会检查它是否有效。我还安装了空间扩展器。但我无法弄清楚在其中存储坐标。让我知道如果你知道任何关于它的信息,这将有很大的帮助..你可以在db2页面的插件中找到空间扩展器。 – 2012-03-24 06:16:40

+0

我已经尝试了上面的查询。它返回给我以下错误 SQL0206N“DIST”在使用它的上下文中无效。 SQLSTATE = 42703 SQL0206N“DIST' – 2012-03-24 20:52:27

相关问题