Matt
Matt

Reputation: 3876

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?

EDIT: Thanks guys, corrected the Longitude part of the query.

Upvotes: 3

Views: 3576

Answers (3)

Arc
Arc

Reputation: 11306

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.

Upvotes: 3

fbstj
fbstj

Reputation: 1714

would

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

work better?

Upvotes: 0

Patrick
Patrick

Reputation: 3172

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;

Upvotes: 6

Related Questions