views:

53

answers:

4

There's a few questions like this on Stack Overflow but because i can't find any quite similar enough for me to follow.

I'm looking to select rows from db which are within x miles of a target.

example table columns:

| city_name(varchar) | lat(decimal) | lon(decimal) |

query effect i'm looking for (either using php or mysql)

$target_lat = ;
$target_lon = ;
"SELECT table.city_name WHERE (table.lat,table.lon) LESS THAN 20 MILES FROM ($target_lat,$target_lon")

obviously i don't expect query to take this structure! (i've never used Pi etc in mysql...)

A: 

you will find many code snippets in google searching for "mysql radius search"

they are a little bit too long for copying here.

Edit: http://spinczyk.net/blog/2009/10/04/radius-search-with-google-maps-and-mysql/

Tobias P.
i'm not finding that much that isn't zip code orientated: http://www.google.co.uk/search?q=mysql+radius+search+coordinates+proximity+-zip
Haroldo
@Tobias perhaps you could post a link for Haraldo
Chief17
@Chief17, @Haroldo: i have added one example in my answer.
Tobias P.
+3  A: 

It sounds like you're looking for a geo-spatial package for mySql. There's a function listed here that allows for distance checking between two lat/long points. Just remember that a regular distance calculation won't work with lat/long because of the Earth's curvature. =)

http://forge.mysql.com/wiki/GIS_Functions

Robert Hui
That looks like a useful package. But, for this purpose, you could use the `Distance` function that's built into MySQL? Docs say `Distance has been implemented properly, unlike some of the other geospatial support. http://dev.mysql.com/doc/refman/5.0/en/functions-that-test-spatial-relationships-between-geometries.html#function_distance
MarkJ
Mark - nice find. I had read a (outdated, most likely) blurb that the geospatial support in mySql was still a little lacking, and offered that alternative. I'm glad to hear that the support is native =).
Robert Hui
A: 

The Pythagorean theorem states that the square of the length of the hypotenuse of a right triangle is equal to the sum of the squares of the other two sides.

C^2 = A^2 + B^2
C = SQRT(A^2 + B^2)

In this case, the lengths of the other sides are determined by the difference of your lat and long values. Over short distances this will give you a pretty good approximation. However, this still doesn't give you miles, which is a much more difficult conversion since there is not a fixed relationship between lat/long and miles. Instead, the distance between longitudes varies as a function of latitude.

GalacticCowboy
+1  A: 

I found this which is brilliant and really easy to understand

http://code.google.com/apis/maps/articles/phpsqlsearch.html

Haroldo