Codeigniter and SQL/Haversine Formula

ぃ、小莉子 提交于 2019-12-24 05:01:49

问题


I am using Codeigniter for a project and have some locations with latitude and longitude inputs on the database. I'm trying to get points within a certain distance (50km), and attempting it with the Haversine Formula. However, on my controller and view it doesn't print out the results. What I need to know is if there's any adjustments I need to make to get the model function working.

Note: The DB table has the column names location_latitude and location_longitude.

//base function to compare distance with
$setlat = 13.5234412; 
$setlong = 144.8320897; 
//query with Haversin formula 
$awaka = "SELECT 'location_id',
    ( 3959 * acos( cos( radians(?) ) * cos( radians('location_latitude') ) * cos( radians('location_longitude') - radians(?) )
    + sin( radians(?) ) * sin( radians('location_latitude') ) ) ) AS 'distance'
    FROM 'locations' HAVING 'distance < 5'";
 $result = $this->db->query($awaka, array($setlat, $setlong, $setlat));  
 echo $result; 

回答1:


It appears you got a little tripped up by the Haversine formula. You switched the $setlong and location_longitude terms in the third cosine term. I switched them around to get this:

$setlat = 13.5234412; 
$setlong = 144.8320897; 
$awaka = "SELECT 'location_id',
    ( 3959 * acos( cos( radians(?) ) * cos( radians('location_latitude') ) * cos( radians(?) - radians('location_longitude') )
    + sin( radians(?) ) * sin( radians('location_latitude') ) ) ) AS 'distance'
    FROM 'locations' HAVING 'distance < 5'";
$result = $this->db->query($awaka, array($setlat, $setlong, $setlat));  
echo $result;

Have a look at this page, which shows you have to code up the Haversine formula to find the distance between two points.




回答2:


This is an Active Records that help you it works for me.

$this->db->select("location_id,round((6371 * acos(cos(radians($setlat)) * cos(radians(location_latitude)) * cos(radians('$setlong') - radians(location_longitude)) + sin(radians('$setlat')) * sin(radians(location_latitude)))),2) AS distance", false);
$this->db->having('distance < 5', false);
$data = $this->db->get('locations')->result_array();
return $data;


来源:https://stackoverflow.com/questions/30366466/codeigniter-and-sql-haversine-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!