在sql中使用lat和long查找距离

时间:2016-03-29 05:42:58

标签: php mysql codeigniter

我想在10点左右搜索任何地方。使用lat和long。我该怎么设置限制?这是我的SQL查询:

$this->db->select(", ( 6371  acos( cos( radians(37) )  cos( radians(latitude) )   cos( radians( longtitude )- radians($lng) ) + sin( radians($lat) ) * sin( radians( latitude) ) ) ) AS distance");                         
$this->db->from('table_name'); 
$this->db->order_by('distance');

3 个答案:

答案 0 :(得分:3)

试试这个:

    $this->db->query('  SELECT  ( 6371 * acos( cos( radians(37) )  cos( radians(latitude) )   cos( radians( longtitude )- radians("'.$lng.'") ) + sin( radians("'.$lat.'") ) * sin( radians( latitude) ) ) ) AS distance 
                        FROM table_name
                        HAVING distance < 10
                        ORDER BY distance ASC');

答案 1 :(得分:0)

Try this:
$this->db->select(", ( 6371  acos( cos( radians(37) )  cos( radians(latitude) )   cos( radians( longtitude )- radians($lng) ) + sin( radians($lat) ) * sin( radians( latitude) ) ) ) AS distance");                         
$this->db->from('table_name'); 
$this->db->having('distance<',10)
$this->db->order_by('distance');

答案 2 :(得分:0)

$sql = 'select *,(((acos(sin(('.$lat.'*pi()/180)) * 
            sin((loc_LAT_centroid*pi()/180))+cos(('.$lat.'*pi()/180)) * 
            cos((loc_LAT_centroid*pi()/180)) * cos((('.$lang.'-loc_LONG_centroid)* 
            pi()/180))))*180/pi())*60*1.1515
        ) AS distance from table_name order by distance';

$lat = latitude of your current location
$lang = longitude of your current location

loc_LAT_centroid = field name of your table where you store the latitude of the places.
loc_LONG_centroid = field name of your table where you store the longitude of the places.