1、用户上传自己的位置信息,服务器根据这个用户的经纬度查询出在指定范围内的标记点按照距离排序返回给用户。
可以用在社区团购选择团长和外卖按照距离排序的餐馆。
初始化
public function __construct(){
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1',6379);
}
计算查询
public function test(){
$arr = Request::instance()->post();
$latitude = $arr['latitude'];
$longitude = $arr['longitude'];
$redis = $this->redis;
try {
$param_a = array('areaCache');
$ret = call_user_func_array(array($redis, 'EXISTS'), $param_a);
if($ret){
$param = array('georadius', 'areaCache', $longitude, $latitude, 55000, 'm', 'WITHDIST', 'WITHCOORD','ASC');
$nearbyList = call_user_func_array(array($redis, 'rawCommand'), $param);
//半径50000、单位m/km可选、距离显示、排序规则
return getjson('1', '查找到排序:', $nearbyList);
}else{
return getjson('1', '没有查询到:','异常!' );
}
} catch (Exception $e){
}
}
2、当我们的数据库中的位置标记点有数据更新时候,更新redis-geo缓存就可以,当系统刚开始的时候或者服务器重启可以把服务器中的数据批量插入到redis-geo中。
$geoInfo = Db::connect('数据库连接')->table('数据库表area')->field('latitude,longitude,wxId,province,city,county,community')->where('status', '1')->select();
foreach ($geoInfo as $k => $v) {
$result = $redis->geoAdd(
"areaCache",
$v['longitude'], $v['latitude'], json_encode($v,320)
);
}
注:
方法:call_user_func_array( callable $callback , array $param_arr )
把第一个参数作为回调函数(callback)调用,把参数数组作(param_arr)为回调函数的的参数传入。