Doing a Radius Search - Code
I've been asked a number of times how to construct a radius search in miles for point coordinates. This is a pretty simple thing to do once it is realized that true circles are hard to deal with using latitude and longitude coordinates. I've found the best method is not to use a circle and a radius but instead construct a circular polygon using a haversine formula to compute the verticies of the polygon from a center point. Here's an example using Perl to compute such a polygon for a radius of 20 miles with a zip code of 38654 as the center point (centroid courtesy of Google Map API Geocoder).
#!/usr/bin/perl -w
use strict ;
my $radius = 20 ;
my $clat = 34.918 ;
my $clng = -89.8215 ;
my $PI = 3.141593 ;
my $d2r = $PI/180 ;
my $r2d = 180/$PI ;
my $lat = ($radius/3963) * $r2d ;
my $lng = $lat/cos($clat * $d2r);
my @points = ( ) ;
my $i = 0 ;
my $x = '' ;
my $y = '' ;
for ($i = 0 ; $i < 13 ; $i++)
{
$y = sprintf("%0.6f",$clng + ($lng * cos($PI * ($i/6)))) ;
$x = sprintf("%0.6f",$clat + ($lat * sin($PI * ($i/6)))) ;
push( @points, [$x,$y] ) ;
}
foreach $x ( @points )
{
print "$$x[0],$$x[1]\n" ;
}
Results of this calculation:
34.918000,-89.468862
35.062577,-89.516106
35.168414,-89.645181
35.207154,-89.821500
35.168414,-89.997819
35.062577,-90.126894
34.918000,-90.174138
34.773423,-90.126894
34.667586,-89.997819
34.628846,-89.821500
34.667586,-89.645181
34.773423,-89.516106
34.918000,-89.468862
This is how it looks on a map:

The same basic code in Javascript can be found in this example page:
Once the polygon has been constructed, the search method depends on the database being used. I prefer Postgres or PostGIS, both of which have exceptional spatial functions built in.
