从纬度和经度到mysql数据库附近

时间:2015-03-04 11:48:16

标签: php codeigniter maps

我的事件数据库有多个事件,每个事件都有不同的纬度和经度,如果我当前的纬度是30.7263962,经度是76.7664144,我如何从数据库中获取距离我位置不到100公里范围的事件?谁能建议我查询?感谢

2 个答案:

答案 0 :(得分:0)

您可以弯曲的一些示例代码(我已经尝试适应您的需求,但已做出一些猜测)。
这是使用Rhumb线(或loxodrome)

的半身算法的一个版本
<?php
function search($device_latitude, $device_longitude, $radius, $radius_type)
{
    $events = array();

    $sql = "SELECT `event_id`, `last_updated`, `location_lat`, `location_long` FROM `event`";
    $query = $this->db->query($sql);

    if ($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
        {
            $geo_data = $this->_bearing_distance_calc($device_latitude, $device_longitude, $row->location_lat, $row->location_long, $radius_type);
            $geo_data['radius_type'] = $radius_type;
            // $geo_data contains => 'distance', 'bearing'
            if($geo_data['distance'] <= $radius)
            {
                $events[] = $this->event->load($row->event_id);
            }
        }
        return $events;
    }
    $this->error_msg = "Search failed.";
    return NULL;
}

function _bearing_distance_calc($device_latitude, $device_longitude, $event_latitude, $event_longitude, $radius_type)
{
    // using Rhumb lines(or loxodrome)
    // convert to rads for php trig functions
    $device_latitude = deg2rad($device_latitude);
    $device_longitude = deg2rad($device_longitude);
    $event_latitude = deg2rad($event_latitude);
    $event_longitude = deg2rad($event_longitude);

    // calculate delta of lat and long
    $delta_latitude = $event_latitude-$device_latitude;
    $delta_longitude = $event_longitude-$device_longitude;

    // earth radius
    if ($radius_type == 'Miles')
    {
        $earth_radius = 3959;
    }
    else
    {
        $earth_radius = 6371;
    }

    // now lets start mathing !!
    $dPhi = log(tan($event_latitude/2+M_PI/4)/tan($device_latitude/2+M_PI/4));
    if ($dPhi != 0)
    {
        $q = $delta_latitude/$dPhi;
    }
    else
    {
        $q = cos($device_latitude);
    }
    //$q = (!is_nan($delta_latitude/$dPhi)) ? $delta_latitude/$dPhi : cos($device_latitude);  // E-W line gives dPhi=0

    // if dLon over 180° take shorter rhumb across 180° meridian:
    if (abs($delta_longitude) > M_PI)
    {
        $delta_longitude = $delta_longitude>0 ? -(2*M_PI-$delta_longitude) : (2*M_PI+$delta_longitude);
    }

    $geo_data = array();
    $geo_data['distance'] = sqrt($delta_latitude*$delta_latitude + $q*$q*$delta_longitude*$delta_longitude) * $earth_radius;
    $bearing = rad2deg(atan2($delta_longitude, $dPhi));

    if($bearing < 0)
    {
        $bearing = 360 + $bearing;
    }
    $geo_data['bearing'] = $bearing;

    return $geo_data;
}

答案 1 :(得分:0)

您需要的是将距离转换为经度和纬度,根据大致在边界框中的条目进行过滤,然后进行更精确的距离过滤。这是一篇很好的论文,解释了如何做到这一切:

http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL