1.项目需求
根据用户的定位,查询距离大约5公里(该距离可以调节)的商家,并显示与用户的距离。
2.思路实现
1.先筛选出来距离5公里的商家,(必须要分页)
2.根据选筛选出来的商家进行距离计算.
3.代码实现
1.获取附近5公里商家(方法可以自己百度)
//查询距离自己5千米的商铺
public function selectcltext(){
$page = I('post.page'); //分页
$relevance = I('post.relevance'); //分类
$size = 10;
$lng = I('post.long');
$lat = I('post.lat');
$point = $this->returnSquarePoint($lng,$lat,50000); //得到四个点
// tp3.2的判断大小经度纬度的判断
$where['relevance'] = array('eq',$relevance);
$where['latitude'] = array(array('gt',$point[minLat]),array('lt',$point[maxLat]));
$where['longitude'] = array(array('gt',$point[minLon]),array('lt',$point[maxLon]));
$res[count] = M('ppjj_cltext')->where($where)->count();
$res[da] = M('ppjj_cltext')->where($where)->page($page,$size)->select();
//查询距离的方法调用
if ($res[count]> 0){
$result = $res[da];
foreach($result as $key => $value){
$distance = $this->getDistance($lat,$value[latitude],$lng,$value[longitude],2,2);
$result[$key]['distance'] = $distance;
}
$res[da] = $result;
$this->ajaxReturn($res);
}else{
echo "none";
}
}
// *@param lng float 经度
// *@param lat float 纬度
// *@param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为单位米
// *@return array 正方形的四个点的经纬度坐标
public function returnSquarePoint($lng, $lat,$distance)
{
$PI = 3.14159265;
$longitude = $lng;
$latitude = $lat;
$degree = (24901*1609)/360.0;
$raidusMile = $distance;
$dpmLat = 1/$degree;
$radiusLat = $dpmLat*$raidusMile;
$minLat = $latitude - $radiusLat; //拿到最小纬度
$maxLat = $latitude + $radiusLat; //拿到最大纬度
$mpdLng = $degree*cos($latitude * ($PI/180));
$dpmLng = 1 / $mpdLng;
$radiusLng = $dpmLng*$raidusMile;
$minLng = $longitude - $radiusLng; //拿到最小经度
$maxLng = $longitude + $radiusLng; //拿到最大经度
$range = array(
'minLat' => $minLat,
'maxLat' => $maxLat,
'minLon' => $minLng,
'maxLon' => $maxLng
);
return $range;
}
2.查询距离方法
// 查询距离
public function getDistance($latitude1,$latitude2,$longitude1,$longitude2,$unit){
$EARTH_RADIUS = 6370.996; // 地球半径系数
$PI = 3.1415926; //
$radLat1 = $latitude1 * $PI / 180.0;
$radLat2 = $latitude2 * $PI / 180.0;
$radLng1 = $longitude1 * $PI / 180.0;
$radLng2 = $longitude2 * $PI /180.0;
$a = $radLat1 - $radLat2;
$b = $radLng1 - $radLng2;
$distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
$distance = $distance * $EARTH_RADIUS * 1000;
if($unit==2){
$distance = $distance / 1000;
}
return $distance;
}
注释:以上所有的方法,百度均可以查到
1.注意自己的判断方法,本人第一次把这个tp3.2的区间查询写错了