2015-07-21 62 views
2

我有一個表中的項目存儲使用基於經度和緯度的地理位置。在某一點上,我只想從數據庫中檢索當前位置特定範圍(距離或半徑)內的項目。Sqlite:選擇基於距離的項目(經度和緯度)

項目(緯度,經度)

所以我跟着這真的nice post,並試圖實現與得票最高的答案。首先:在存儲項目時,我不得不添加更多的列。這使得select語句後面:

項目(LAT,lat_cos,lat_sin,LNG,lng_cos,lng_sin)

到目前爲止好,但是當我再嘗試構建查詢,我瘋了。如果我使用較少符號<則檢索所有項目(即使太遠)。但是,如果我使用更大的符號>,則不會檢索任何項目。但我知道我的範圍內有物品。

問題:那麼我在做什麼錯了?

WHERE(coslat * LAT_COS *(* LNG_COS + coslng * LNG_SIN sinlng))+ sinlat * LAT_SIN> cos_allowed_distance

下面是我使用的查詢我的ContentProvider的代碼。該ContentInfo類有中將sortOrder,選擇字段和selectionArgs兩個:

public static ContentInfo buildDistanceWhereClause(double latitude, double longitude, double distanceInKilometers) { 

     final double coslat = Math.cos(Math.toRadians(latitude)); 
     final double sinlat = Math.sin(Math.toRadians(latitude)); 
     final double coslng = Math.cos(Math.toRadians(longitude)); 
     final double sinlng = Math.sin(Math.toRadians(longitude)); 

     // (coslat * LAT_COS * (LNG_COS * coslng + LNG_SIN * sinlng)) + sinlat * LAT_SIN > cos_allowed_distance 
     final String where = "(? * ? * (? * ? + ? * ?)) + ? * ? > ?"; 
     final String[] whereClause = new String[] { 
       String.valueOf(coslat), 
       ItemTable.COLUMN_LATITUDE_COS, 
       ItemTable.COLUMN_LONGITUDE_COS, 
       String.valueOf(coslng), 
       ItemTable.COLUMN_LONGITUDE_SIN, 
       String.valueOf(sinlng), 
       String.valueOf(sinlat), 
       ItemTable.COLUMN_LATITUDE_SIN, 
       String.valueOf(Math.cos(distanceInKilometers/6371.0)) 
     }; 

     return new ContentInfo(null, where, whereClause); 
    } 
} 

回答

2

我沒有真正看到問題,但我重新設計了選擇/在那裏,以便更容易閱讀。現在它起作用了。您還可以結賬this fiddle

public static String buildDistanceWhereClause(double latitude, double longitude, double distanceInKilometers) { 

    // see: http://stackoverflow.com/questions/3126830/query-to-get-records-based-on-radius-in-sqlite 

    final double coslat = Math.cos(Math.toRadians(latitude)); 
    final double sinlat = Math.sin(Math.toRadians(latitude)); 
    final double coslng = Math.cos(Math.toRadians(longitude)); 
    final double sinlng = Math.sin(Math.toRadians(longitude)); 

    final String format = "(%1$s * %2$s * (%3$s * %4$s + %5$s * %6$s) + %7$s * %8$s) > %9$s"; 
    final String selection = String.format(format, 
      coslat, COLUMN_LATITUDE_COS, 
      coslng, COLUMN_LONGITUDE_COS, 
      sinlng, COLUMN_LONGITUDE_SIN, 
      sinlat, COLUMN_LATITUDE_SIN, 
      Math.cos(distanceInKilometers/6371.0) 
      ); 

    Log.d(TAG, selection); 
    return selection; 
} 
+0

嗨。我在你的問題中遇到了同樣的問題。無值或全部值。這是一個可行的解決方案嗎?什麼是ContentInfo?請幫助 – Jas

+0

我更改了代碼並刪除了我的數據結構ContentInfo。你只需要字符串「選擇」。代碼工作正常,是的。我在我的應用程序中使用它。 – Matthias

相關問題