3

hay all .. i have a customers table in my android database .. i am currently using room persistance, i am looking to take all my customers data .. but sequential from start location to nearest me at the moment .. how to query for it my case example .. My current latitude is -7.3530829 , my longitude is currently 112.6901788

    data in my customers table
    customers.address = "Waterpark Boulevard Citraland Area
    customers.handphone1 = "0857887328"
    customers.latitude = -7.2864881
    customers.longitude = 112.6525076


    data in my customers table
    customers.address = "Nature Conservation Area
    customers.handphone1 = "0857887328"
    customers.latitude = -7.3571553
    customers.longitude = 112.6862058


    data in my customers table
    customers.address = "Kawasan Taman Pinang
    customers.handphone1 = "0857887328"
    customers.latitude =
            -7.3403807
    customers.longitude = 112.6914085

   //get Data by Name,,
   @Query("SELECT * FROM customers WHERE name = :name")
   abstract fun findByName(name:String): MutableList<Customers>

   //How to retrieve data based on the closest distance ?
   @Query("SELECT ???")
   abstract fun findByDistance(mylatitude:Double,mylongitude:Double): MutableList<Customers>

please help to findByDistance query ..

abdul
  • 121
  • 1
  • 8
  • yes it may be the same but it is actually a different way ,, because i search it with mysql query – abdul Feb 01 '18 at 04:24

1 Answers1

6

I've found the right query by calculating the straight distance..

@Query("SELECT * FROM customers ORDER BY ABS(latitude - :latitude) + ABS(longitude - :longitude) ASC")
abstract fun findByDistance(latitude:Double,longitude:Double): MutableList<Customers>

Maybe this can help you who need the same thing as me.. thank you..

abdul
  • 121
  • 1
  • 8
  • it's works properly in one of my testing. good job! – hedzr Aug 27 '18 at 02:52
  • The distance calculation here doesn't properly calculate the distance, since something that is two degrees of longitude away can be closer than something one degree of latitude away (especially the closer you get to the poles). The proper way to calculate the distance would be with the [great circle distance](https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula). However, the approach listed here is enough for most applications. – Emil S. May 27 '22 at 14:19