开发者

Find locations within a lat/lng bounding box

I have 4 variables:

$southwest_lat, $southwest_lng, $northeast_lat, $northeast_lng

I also have a database table, with fields: Name, Latitude, and 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')";

How would I find DB items within the boundary box formed by the coordinates?

EDI开发者_如何转开发T: Thanks guys, corrected the Longitude part of the query.


You are comparing the latitude & longitude in the database to JUST the latitudes of the submitted values.

Also, you don't need any parentheses in the query, it just makes it cluttered and more complicated.

You want something like:

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


In case your application can have $southwest_lng > $northeast_lng (180 degrees wrap-around, e.g. when using Google Maps), you may want to check that and use a NOT BETWEEN $northeast_lng AND $southwest_lng in that case.


would

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

work better?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜