1
votes

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!

1

1 Answers

1
votes

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 = "
SELECT 
    name,
    ((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 

FROM 
    yourtable 

WHERE 1 
    AND name like 'John%'

HAVING distance <=7
ORDER BY distance ASC
LIMIT 10";