在lat / lng边界框中查找位置

时间:2011-03-25 19:55:07

标签: php mapping latitude-longitude

我有4个变量:

$ southwest_lat,$ southwest_lng,$ northeast_lat,$ northeast_lng

我还有一个数据库表,其中包含字段:Name,Latitude和Longitude。

// First attempt, likely terribly wrong
$sql = "SELECT * FROM items WHERE
(Latitude >= '$southwest_lat' AND Latitude <= '$northeast_lat') AND
(Longitude >= '$southwest_lng' AND Longitude <= '$northeast_lng')";

如何在坐标形成的边界框内找到数据库项目?

编辑:谢谢大家,更正了查询的经度部分。

3 个答案:

答案 0 :(得分:6)

您正在比较纬度和&amp;数据库中的经度只是提交值的纬度。

此外,您在查询中不需要任何括号,只会使它变得杂乱而且更复杂。

你想要这样的东西:

SELECT 
    *
FROM 
    items
WHERE
    Latitude >= $southwest_lat AND
    Latitude <= $northeast_lat AND
    Longitude >= $southwest_long AND
    Longitude <= $northeast_long;

答案 1 :(得分:3)

如果您的应用可以$southwest_lng&gt; $northeast_lng(180度环绕,例如在使用Google地图时),您可能需要检查并在这种情况下使用NOT BETWEEN $northeast_lng AND $southwest_lng

答案 2 :(得分:1)

SELECT * FROM items 
WHERE Latitude BETWEEN $southwest_lat AND $northeast_lat 
AND Longitude BETWEEN $southwest_lng AND $northeast_lng

工作得更好?

相关问题