How to retrieve a set of locations within particular range from user's location from SQLite database

后端 未结 2 994
灰色年华
灰色年华 2021-01-16 11:35

I have some location coordinates stored in my SQLite database table. I want to retrieve the locations within 1 km range from the use\'s current location. Right

2条回答
  •  自闭症患者
    2021-01-16 12:25

    You can write a SQL query with following where condition :

    where ( (my_lat - LAT)*(my_lat - LAT) + (my_lon - LON)*(my_lon - LON) ) <= 1KM
    

    The idea is that use Pythagoras method to calculate approx location and filter based on that. Here I have not taken the square root because I guess SQL functions in SQLite don't have sqrt.

    This is good for approximate calculations ...

    I used following SQL and it worked ...

    // Table with columns as String and Float
    CREATE TABLE "locations" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , "lat_string" VARCHAR, "long_string" VARCHAR, "lat_val" FLOAT, "long_val" FLOAT)
    
    // Insert example data
    INSERT INTO "locations" VALUES(1,'12.9587926','77.7477416',12.9587926,77.7477416);
    INSERT INTO "locations" VALUES(2,'12.9973486','77.6967362',12.9973486,77.69673619999999);
    INSERT INTO "locations" VALUES(3,'12.9715987','77.5945627',12.9715987,77.5945627);
    INSERT INTO "locations" VALUES(4,'12.9629354','77.7122996',12.9629354,77.7122996);
    
    // Select when column format is string. This works in SQLIte
    SELECT id, ( (77.7580827 - long_string)*(77.7580827 - long_string) + (12.9905542 - lat_string)*(12.9905542 - lat_string) ) as dist FROM locations
    
    // Select when column format is float. This works in SQLIte
    SELECT id, ( (77.7580827 - long_val)*(77.7580827 - long_val) + (12.9905542 - lat_val)*(12.9905542 - lat_val) ) as dist FROM locations
    

提交回复
热议问题