2012-03-22 38 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