Search code examples
androidmysqlsqlsql-serverandroid-sqlite

haversine formula definition for sql


Hi iam currently working on an android app which stores the details of shops in an sql database and the users use the app to search for the shops around them.

i found a formula called haversine to find distance between two points with there lat and lng values.

    SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians(         lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM     markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

but iam confused with this i don't know which lat and lng value refers to what! if some one could re-write the above code such that my user has position lat1 & lng1 for the shopkeeper it is lat2 and lng2. Also can u tell me what is that a in

  acos 

Solution

  • The order of lat/lngs don't matter. Think of it this way... the distance from point A to point B is that same as the distance from point B to point A.

    In your code example, the 37 is a latitude point and the -122 is a longitude point.

    acos is the arc cosine trigonemetric function. Explanation here: ArcCosine

    SELECT id, ( 3959 * acos( cos( radians(Lat1) ) * cos( radians( Lat2 ) ) * cos( radians(Lng2) - radians(Lng1) ) + sin( radians(Lat1) ) * sin( radians(Lat2)))) AS distance 
    FROM     markers 
    HAVING distance < 25 
    ORDER BY distance 
    LIMIT 0 , 20;