Reputation: 558
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..
Upvotes: 3
Views: 1010
Reputation: 1825
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";
Upvotes: 2