Question

I have got a very basic store locator script. which the user enters postcode/zip-code that is converted to lat and long and then searched in the database to find the nearest stores.

my current SQL:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
FROM markers
HAVING distance < 500
ORDER BY distance
LIMIT 0 , 100;

As you can see this does work, but its limited to a range of 500 miles, i want to remove the limit. if i try remove HAVING distance < 500 , the distance is returned as NULL.

I need the results to says Store name XX miles away.

Another question, can this query be optimized? i have lat and long cols in the database as index.

Was it helpful?

Solution

The distance is NULL because some of your records have NULL values for lat and/or lng. You can add:

HAVING distance is not null

until you fix the problem.

If you want to optimize the query, then think about using the geospatial extensions (the documentation is here).

OTHER TIPS

You can Query :

// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));
$result = mysql_query($query);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top