给定地理区域内的Mysql查询

时间:2013-09-30 18:55:04

标签: mysql sql geo

我的数据库中的一个表包含许多邮政地址,这些地址也有这样的经度和纬度信息:

姓名----街道地址--------邮政编码----经度----纬度

弗雷德---- 11 Monarch Street ----- 4114 ---------- 57.317715 ---- 10.154355

巴尼 - 4 Reign Street -------- 4114 ------------ 56.151112 ---- 10.087925

我有一个给定的区域(通过谷歌地图的kml坐标),定义如下:

        12.548740,55.694469,0.000000
        12.541320,55.687840,0.000000
        12.537410,55.690552,0.000000
        12.535310,55.694641,0.000000
        12.534499,55.695293,0.000000
        12.535787,55.696625,0.000000
        12.538100,55.696911,0.000000
        12.543890,55.697659,0.000000
        12.548740,55.694469,0.000000

我用什么mysql查询来查找该区域内的地址?

1 个答案:

答案 0 :(得分:0)

我不知道任何MySQL查询。

在这个Answer中我使用PHP函数来查找一个点是否在多边形中(4个点)。该函数基于C代码Point in Polygon Darel Rex Finley

您可以将它用于8点多边形。

$polySides  = 8; //how many corners the polygon has
$polyX    =  array(12.548740,12.541320,12.537410,12.535310,12.534499,12.535787,12.538100,12.543890,12.548740);//horizontal coordinates of corners
$polyY    =  array(55.694469,55.687840,55.690552,55.694641,55.695293,55.696625,55.696911,55.697659,55.694469);//vertical coordinates of corners
$x = 12.548740; 
$y = 55.694469;//Inside
//$y = 12.528740;//Outside

function pointInPolygon($polySides,$polyX,$polyY,$x,$y) {
  $j = $polySides-1 ;
  $oddNodes = 0;
  for ($i=0; $i<$polySides; $i++) {
    if ($polyY[$i]<$y && $polyY[$j]>=$y 
 ||  $polyY[$j]<$y && $polyY[$i]>=$y) {
    if ($polyX[$i]+($y-$polyY[$i])/($polyY[$j]-$polyY[$i])*($polyX[$j]-$polyX[$i])<$x)    {
    $oddNodes=!$oddNodes; }}
   $j=$i; }

  return $oddNodes; }


 if (pointInPolygon($polySides,$polyX,$polyY,$x,$y)){
  echo "Is in polygon!";
}
else echo "Is not in polygon";

您可以在数据库中循环插入lat,lng到函数中。

如果数据库很大,您可以使用north_west和south_east创建一个边界框 坐标以限制函数过滤的数据。

$sql = "SELECT lat,lng FROM `table` WHERE (lng BETWEEN '$west_lng' AND '$east_lng') AND (lat BETWEEN '$north_lat' AND '$south_lat')";

另一种解决方案是使用mysql spatial extension