Take the 2-minute tour ×

I have a sql database search that currently has a search term and an address input - which is geocoded by google for lat/lng. Right now, I order the results first by relevance to the search term, and then by distance, based on a static radius (7 miles).

The problem I have is that if you search "Joe Smith" near "Central Park", there could be a "Joe Smith" in the Bronx (within the static 7 miles) that comes up as the first result, instead of all the Joes and Smiths that are actually in Central Park. Is there a way to automatically change this currently static search radius based on how large the area is that is searched, so that it would work for New York City, or even New York state? Or is there a better solution to this problem?

I guess what I'm trying to do is mimic the search on google maps, so that I can have the most relevant searches first, but in the actual area that was searched. Any help at all would be greatly appreciated, or even some different approaches that I should take. Thanks!

share|improve this question
add comment

1 Answer

Presuming you have the columns name, longitude and latitude, you can do the following query to get the results ordered by distance:

// Long/Lat of the geocoded address (In your case: Central Park)
$latitude = 40.771133;
$longitude = -73.974187;

$sql = "
    ((ACOS(SIN( ".$latitude." * PI() / 180) * SIN(latitude * PI() / 180) + COS(".$latitude." * PI() / 180) * COS(latitude * PI() / 180) * COS((".$longitude." - longitude) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance 


    AND name like 'John%'

HAVING distance <=7
ORDER BY distance ASC
LIMIT 10";
share|improve this answer
add comment

Your Answer


