tpshop商城根据用户坐标,向数据库查找附近的商家

前不久要实现这个功能,刚好tpshop商城里面有根据用户坐标,向数据库查找附近的商家。顺便记录网上找到的一些方法,以便以后使用。
使用TP框架
<?php
/**
 * 计算某个经纬度的周围某段距离的正方形的四个点
 * 地球半径,平均半径为6371km
 * @param lng float 经度
 * @param lat float 纬度
 * @param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米
 * @return array 正方形的四个点的经纬度坐标
 */
function getAroundCoordinate($lng, $lat,$distance = 0.5){

    $dlng =  2 * asin(sin($distance / (2 * 6371)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);

    $dlat = $distance/6371;
    $dlat = rad2deg($dlat);

    return array(
        'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
        'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
        'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
        'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
    );
}
虚拟数据结果


//调用上面函数
public function actionGetNearShop(){
$scope = 5;//5000米
$lng = trim(I('lng/s')); //经度
$lat = trim(I('lat/s')); //纬度
$fourpoint= getAroundCoordinate($lng,$lat,$scope);
//从数据库中查询此范围内商铺
$where = "longitude>".$fourpoint['right-bottom']['lat']." and longitude<".$fourpoint['left-top']['lat']." and latitude<".$fourpoint['left-top']['lng']." and latitude>".$fourpoint['right-bottom']['lng'];
$storeCoordinate = M('store')->where($where)->column('store_id,store_name,longitude,latitude','store_id');
foreach ($storeCoordinate as $k =>$v){
   if(sqrt((pow((($lat - $v['latitude'])* 111),2))+(pow((($lng - $v['longitude'])* 111),2))) <= 5){
     $storeCoordinate[$v['store_id']]['distance'] = sqrt((pow((($lat - $v['latitude'])* 111000),2))+(pow((($lng - $v['longitude'])* 111000),2)));
   }
}
   echo json_encode($storeCoordinate);
}
TPshop商城多商家版本的部分代码

 



/**
* 根据百度坐标,获取周边商家
* @param $lng 经度
* @param $$lat 纬度
* @param $scope 范围 千米
* @return array $fourpoint
* */
public function index(){
$lng =trim(I('lng/s',114.067345)); //经度
$lat =trim(I('lat/s',22.632611)); //纬度
$scope = trim(I('scope/d',5)); //5千米
//需要分页,统计符合条件的总数量
$count= Db::query("SELECT COUNT(store_id) as num FROM tp_store WHERE SQRT((POW((($lng - longitude)* 111),2))+ (POW((($lat - latitude)* 111),2)))<=$scope");
$Page=new Page($count[0]['num'],10);
//查出需要的数据和坐标与商家的距离
$store=Db::query("SELECT store_id,store_name,round(SQRT((POW((($lng - longitude)* 111),2))+(POW((($lat - latitude)* 111),2))),2) AS distance FROM `__PREFIX__store` WHERE SQRT((POW((($lng - longitude)* 111),2))+(POW((($lat - latitude)* 111),2))) <=$scope LIMIT {$Page->firstRow},{$Page->listRows}");
return $store;
}
代码源于,tpshop商城有兴趣的朋友可以下载看看
此处还有二开视频:pan-baidu.tpshop.cn

posted on 2017-04-14 22:56  donaldbase  阅读(1178)  评论(0编辑  收藏  举报

导航