如何定义lat / lng位置周围的径向搜索区域?

时间:2012-01-16 11:37:21

标签: php mysql google-maps google-maps-api-3

我正在开发一个项目,每个用户都有自己的坐标lat / lng,从谷歌地理编码器服务中提取......

现在我想实现一个搜索功能 - >您可以输入半径(km),如果有人在半径范围内,则会弹出配置文件...

当搜索区域实际上是一个正方形时,难以让它工作,但是我如何使用圆圈作为搜索区域?

这里是代码,用于构建mysql查询的“搜索”部分:

// This is the location of the user who submitted the search function.
mysql_select_db("$db_profile");
$sql = "SELECT location_lat,
            location_lng
    FROM location
    WHERE id = '$global_id'";
$sql = mysql_query($sql);   
$row = mysql_fetch_array($sql);

// The coordinates of the user.
$lat = $row['location_lat'];
$lng = $row['location_lng'];

// the entered radius in kilometers - here it is converted to degree (1° = 111km).
$x_degree = $global_search_radius_value / 111;

// define the search grid (it is a squere! but I want a circle!).
$lat_neg = $lat - $x_degree;
$lat_pos = $lat + $x_degree;

$lng_neg = $lng - $x_degree;
$lng_pos = $lng + $x_degree;

// build the search part of the mysql query
$heredoc_search_radius = <<<EOD
AND ($db_profile.location.location_lat > '$lat_neg' 
    AND $db_profile.location.location_lat < '$lat_pos'
    AND $db_profile.location.location_lng > '$lng_neg'
    AND $db_profile.location.location_lng < '$lng_pos')
EOD;

我怎样才能使用圆圈代替squere!?

2 个答案:

答案 0 :(得分:0)

为了保持这种性能,最好的办法是将您的数据放入Apache Solr http://lucene.apache.org/solr/features.html等系统中,这样您就可以开箱即用地进行地理空间搜索。

Solr将确保您的查询保持快速,无论您拥有多少数据点。

答案 1 :(得分:0)

http://en.wikipedia.org/wiki/Pythagorean_theorem

在mysql中它看起来像这样,如果ABS是必要的话,不是suer,理论上它不应该是。

WHERE SQRT(POW(ABS($db_profile.location.location_lat - $lat), 2) + POW(ABS($db_profile.location.location_lng - $lng), 2)) < $radius

如果您需要更快的搜索,请在其他表中保留计算的距离。但是,这将使用n ^ 2行来存储。