3

I have venues in the database that I store with their latitude and longitude.

I also have the logged in user's latitude and longitude.

I'm developing a function that will allow them to find venues within any given measurement, say 20 miles.

Is it possible to find the outermost lat and long of say 20 miles from the user's lat and long and then somehow write a query to find venues within the circle of distance in MySQL?

Thanks.

sark9012
  • 5,485
  • 18
  • 61
  • 99
  • 1
    There's thousands of answers to this question if you simply search: good keywords are "Haversine" or "Vincenty" – Mark Baker Apr 19 '13 at 16:01
  • If you're doing a large number of these calculations, you may consider using a spatially-capable database like PostGIS or MongoDB, which will do these calculations for you. – Alex Howansky Apr 19 '13 at 16:05
  • I see the link @insertusernamehere but that would require me to loop through every value in the database? I'm looking for a way to calculate 20 miles out from the user's location in lat and long and then search the database for what's inside the circle! – sark9012 Apr 19 '13 at 16:08
  • Preselect your data using a *square* instead of a circle. – nibra Apr 19 '13 at 16:30
  • Would the corners of the square be further than the desired distance? – sark9012 Apr 19 '13 at 16:37
  • @Luke - they would, but a bounding box allows you to execute the SQL query against a small subset of your database rows rather than having to execute a slow, expensive haversine or vincenty calculation against every row – Mark Baker Apr 19 '13 at 21:21

2 Answers2

2

I found a working PHP function:

function getDistanceBetweenPoints($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') {

    $theta = $longitude1 - $longitude2;
    $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $distance = acos($distance);
    $distance = rad2deg($distance);
    $distance = $distance * 60 * 1.1515; switch($unit) {
        case 'Mi': break; case 'Km' : $distance = $distance * 1.609344;
    }
    return (round($distance,2));

}  

Thought this may help others.

sark9012
  • 5,485
  • 18
  • 61
  • 99
1

I use this (ported to Objective-C from javascript) - lots of great location equations expressed in javascript http://www.movable-type.co.uk/scripts/latlong.html

codebrane
  • 4,290
  • 2
  • 18
  • 27