kpax
kpax

Reputation: 35

Using geolocation, sort results by distance

Hi I want to refine my "search by geolocation" for my platform( http://carrotleads.com) .

I am able to receive the geolocation of a user who lands on my site. Using his IP, I can get the below JSON http://www.freegeoip.net/json/ This is not always consistent as sometimes some fields don't get populated.

My database has customer records that references their area of operation.

How do I calculate the distance of the user to each of my customer and sort the search results in ascending order by distance ( closest customers/entities displayed first.)

For ex: http://farmersmarkets.org.au/markets

displays all markets in my state sorted alphabetically. How can the results be displayed, sorted by distance.

I code on the LAMP stack but happy to look at examples in other languages and adapt it.

Upvotes: 0

Views: 978

Answers (1)

Nebez Briefkani
Nebez Briefkani

Reputation: 146

Pretty interesting question.
Did some searching and I found this cool article: http://aravindtrue.wordpress.com/2009/06/30/calculate-distance-using-latitude-and-longitude-php-mysql/

The author posts a function in PHP for finding the distance between 2 points using longitude and latitude. This is really convenient since the freegeoip api you've listed returns long/lat.

function getDistanceBetweenPointsNew($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));
}

He also goes on to list an example SQL query that will return results within a distance

$qry = "SELECT *,(((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 `MyTable` 
WHERE distance <= ".$distance."

Definitely check out that article, I think it contains exactly all the information you're looking for.

Upvotes: 1

Related Questions