使用Php获取最近的地点?

时间:2012-01-10 05:11:09

标签: php mysql

嗨在我的数据库中,我在这50个地点共有100个地点离我最近另外50个地点对我来说最长,所以我想用这个顺序对数据进行排序所以我在这里计算距离

$latt=$_REQUEST['latt'];
$long=$_REQUEST['long'];

$start=$_REQUEST['start'];
 function distancefind($lat1, $lon1, $lat2, $lon2, $unit) { 

  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}



 $c=0;
    $limt=10;
    if($start!=null)
    {
    $query="select * from  tbl_MapDetails LIMIT $start,$limt";
    }
$result=mysql_query($query);
if($result)
{
while($row=mysql_fetch_array($result))
{

$distance1=distancefind($latt,$long,$row['Latitude'],$row['Longitude'],"");


$message[$c]=array("ID"=>$row['LocationID'],"Address"=>$address,"City"=>$row['City']=($row['City'] != null)?$row['City']:"","State"=>$row['State']=($row['State'] !=null)?$row['State']:"","Country"=>$row['Country']=($row['Country']!=null)?$row['Country']:"","Zip"=>$row['Zip']=($row['Zip'] !=null)?$row['Zip']:"","Country"=>$row['Country']=($row['Country']!=null)?$row['Country']:"","Distance"=>$distance1=($distance1==null)?"0":$distance1,"Latitude"=>$row['Latitude']=($row['Latitude']!=null)?$row['Latitude']:"","Longitude"=>$row['Longitude']=($row['Longitude']!=null)?$row['Longitude']:"","Pic"=>$pic,"rating"=>$row1[0]=($row1[0]!=null)?$row1[0]:"","name"=>$row['LocationName']=($row['LocationName']!=null)?$row['LocationName']:"","note"=>$row['Note']=($row['Note']!=null)?$row['Note']:"","feature1"=>$row['FeatureIcon1']=($row['FeatureIcon1']!=null)?$row['FeatureIcon1']:"","feature2"=>$row['FeatureIcon2']=($row['FeatureIcon2']!=null)?$row['FeatureIcon2']:"","feature3"=>$row['FeatureIcon3']=($row['FeatureIcon3']!=null)?$row['FeatureIcon3']:"","selectLogo"=>$row['SelectIcon']=($row['SelectIcon']!=null)?$row['SelectIcon']:"");
$c++;
}

所以在这里我得到每次我得到10个位置所以消息数组数据从最接近最长开始如何检查请指导我

感谢您提前

2 个答案:

答案 0 :(得分:1)

如果你想做排序第一次和限制第二次(即选择$limt最接近的事物(由$start偏移)到($lat,$long)),你可以在MySQL中做到这一点:

$query = "SELECT *,
 ((ACOS(  SIN($lat*PI()/180)*SIN(Latitude*PI()/180) 
        + COS($lat*PI()/180)*COS(Latitude*PI()/180)*COS(($long-Longitude)*PI()/180
        )
  ) * 180/PI()
 )*60 * 1.1515) AS dist
FROM  tbl_MapDetails
ORDER BY dist 
LIMIT $start,$limt";

但是,如果您想要$limt 第一然后按距离排序(请选择$limt项,然后按距离排序 - 可能不包含最近的位置),使用@ SergeyRatnikov的答案,或者你需要做一个嵌套的选择:

SELECT * from
 (SELECT *,
   ...[distancecalculation]... AS dist
   FROM tbl_MapDetails
   LIMIT $start,$limt)
ORDER BY dist

答案 1 :(得分:0)

此代码按距离排序数组$ message

function cmp($a, $b) {
    if ($a["Distance"] == $b["Distance"]) {
        return 0;
    }
    return (floatval($a["Distance"]) < floatval($b["Distance"])) ? -1 : 1;
}

uasort($message, 'cmp');