使用地理定位,按距离对结果进行排序

时间:2014-05-26 00:25:41

标签: javascript php mysql

您好我想为我的平台(http://carrotleads.com)优化我的“地理位置搜索”。

我能够收到登陆我网站的用户的地理位置。使用他的IP,我可以获得以下JSON http://www.freegeoip.net/json/ 这并不总是一致的,因为有时某些字段不会被填充。

我的数据库包含引用其运营区域的客户记录。

如何计算用户与我的每个客户的距离,并按距离按升序排序搜索结果(最近显示的客户/实体最近。)

对于前: http://farmersmarkets.org.au/markets

按字母顺序显示我州的所有市场。如何显示结果,按距离排序。

我在LAMP堆栈上编码,但很高兴看到其他语言的示例并进行调整。

1 个答案:

答案 0 :(得分:1)

非常有趣的问题。
做了一些搜索,我找到了这篇很酷的文章:http://aravindtrue.wordpress.com/2009/06/30/calculate-distance-using-latitude-and-longitude-php-mysql/

作者在PHP中发布了一个函数,用于使用经度和纬度查找2个点之间的距离。这非常方便,因为你列出的freegeoip api返回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));
}

他还继续列出一个示例SQL查询,该查询将在距离

内返回结果
$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."

绝对查看那篇文章,我认为它包含了您正在寻找的所有信息。

相关问题