简体   繁体   中英

Sql for finding the distance between using latitude and longitude returns wrong distance

i need to get the distance between location of the latitude and longitude, mysql query works without error but it returns the wrong distance value

When i enter the same latitude and longitude as in the database it gives the distance as "2590.4238273460855" instead of zero, i dont known whats wrong in this

mysql query is as given below here latitude and longitude are my table column name

$sql = "SELECT id,(3956 * 2 * ASIN(SQRT( POWER(SIN(( $latitude - latitude) *  pi()/180 / 2), 2) +COS( $latitude * pi()/180) * COS(latitude * pi()/180) * POWER(SIN(( $longitude - longitude ) * pi()/180 / 2), 2) ))) as distance  
from table_name ORDER BY distance limit 100";

can anyone help me please..

There is an error in your Haversine formula. Haversine formula is:

Haversine_distance= r * 2 * ASIN(SQRT(a))

where

a = POW(SIN(latDiff / 2), 2) + COS(lat1) * COS(lat2) * POW(SIN(LonDiff / 2), 2)

Therefore, to correct your code change your query to:

"SELECT id,(3956 * 2 * ASIN(SQRT( POWER(SIN(( $latitude - latitude) / 2), 2) +COS( $latitude) * COS(latitude) * POWER(SIN(( $longitude - longitude ) / 2), 2) ))) as distance from table_name ORDER BY distance limit 100";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM