使用邮政编码进行半径搜索

时间:2014-01-03 14:15:00

标签: php sql

我使用以下查询进行Radius搜索。

$sqlstring2 = "SELECT DISTINCT 
  geodb.postcode,
  (
    6367.41 * SQRT(
      2 * (
        1- COS(RADIANS(geodb.latitude)) * COS(".$lat.") * (
          SIN(RADIANS(geodb.longitude)) * SIN(".$lng.") + COS(RADIANS(geodb.longitude)) * COS(".$lng.")
        ) - SIN(RADIANS(geodb.latitude)) * SIN(".$lat.")
      )
    )
  ) AS Distance 
FROM
  geodb AS geodb 
WHERE (
    6367.41 * SQRT(
      2 * (
        1- COS(RADIANS(geodb.latitude)) * COS(".$lat.") * (
          SIN(RADIANS(geodb.longitude)) * SIN(".$lng.") + COS(RADIANS(geodb.longitude)) * COS(".$lng.")
        ) - SIN(RADIANS(geodb.latitude)) * SIN(".$lat.")
      )
    ) <= '".$radius."'
  ) 
ORDER BY Distance ";

这个查询有什么问题吗?谁能在这方面帮助我?

由于

更新

我正在使用以下代码

<?php
$postcode = 'E1 0AA';
$radius = 1;

$conn = mysql_connect('127.0.0.1','root','') or die('db connect error:'.mysql_error());
mysql_select_db('database', $conn) or die('could not select database');

$sqlstring = "SELECT * FROM geodb WHERE postcode ='".$postcode."'";
$result = mysql_query($sqlstring);   

$row = mysql_fetch_assoc($result);

$lng = $row["longitude"] / 180 * M_PI;
$lat = $row["latitude"] / 180 * M_PI;

mysql_free_result($result);    

$sqlstring2 = "SELECT DISTINCT geodb.postcode, (6367.41*SQRT(2*(1-cos(RADIANS(geodb.latitude))*cos(".$lat.")*(sin(RADIANS(geodb.longitude))*sin(".$lng.")+cos(RADIANS(geodb.longitude))*cos(".$lng."))-sin(RADIANS(geodb.latitude))* sin(".$lat.")))) AS Distance FROM geodb AS geodb WHERE (6367.41*SQRT(2*(1-cos(RADIANS(geodb.latitude))*cos(".$lat.")*(sin(RADIANS(geodb.longitude))*sin(".$lng.")+cos(RADIANS(geodb.longitude))*cos(".$lng."))-sin(RADIANS(geodb.latitude))*sin(".$lat."))) <= '".$radius."') ORDER BY Distance";

$result1 = mysql_query($sqlstring2) or die('query failed: ' . mysql_error());

echo  mysql_num_rows($result1);

die();

此代码为我提供了结果

1215

但如果我搜索

http://www.freemaptools.com/find-uk-postcodes-inside-radius.htm

邮政编码E1 0AA 半径1英里 我得到结果4(E1,E1W,E77,E98)。

有谁可以说问题在哪里?

谢谢

1 个答案:

答案 0 :(得分:2)

通过对每条记录执行一次计算来减少工作量

$sqlstring2 = "SELECT DISTINCT 
  geodb.postcode,
  (
    6367.41 * SQRT(
      2 * (
        1- COS(RADIANS(geodb.latitude)) * COS(".$lat.") * (
          SIN(RADIANS(geodb.longitude)) * SIN(".$lng.") + COS(RADIANS(geodb.longitude)) * COS(".$lng.")
        ) - SIN(RADIANS(geodb.latitude)) * SIN(".$lat.")
      )
    )
  ) AS Distance 
FROM
  geodb AS geodb 
HAVING Distance <= '".$radius."'
ORDER BY Distance ";

通过在PHP中计算bounding box并将其作为SQL查询中的WHERE子句应用来进一步减少它