Search code examples
pythonmysqlgeolocationlatitude-longitude

Find long/lat's within 20 miles of user's long/lat


I'm working on an application where a user can search for items near his location.

When a user registers for my service, their long/lat coordinates are taken (this is actually grabbed from a zip/postcode and then gets looked up via Google for the long/lats). This also happens when a user adds an item, they are asked for the zip/postcode of the item, and that is converted to the long/lat.

My question is how would i run a query using MySQL that would search within, say 20 miles, from the user's location and get all the items within that 20 mile radius?


Solution

  • Assuming precision isn't really an issue (taking a square instead of a circle, and ignoring terrain), you could do something like this:

    SELECT ... FROM ...
    WHERE (ABS(firstLong - secondLong) < 20) AND (ABS(firstLat - secondLat) < 20);
    

    If you do wish to make it a circle instead, just write a slightly more complicated mathematical formula for the distance: SQRT(longDelta*longDelta + latDelta*latDelta) < 20