从mysql数据库中获取纬度和经度


get nearby from mysql database with latitude and longitude

我有一个包含多个事件的事件数据库,每个事件都有不同的纬度和经度,如果我当前的纬度是30.7263962,经度是76.7664144,我如何从数据库中获取距离我所在位置100公里以内的事件?有人能建议我查询吗?感谢

有些示例代码你可以接受(我曾试图适应你的需求,但做出了一些猜测)
这是haversine算法的一个版本,使用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;
}

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

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