PHP 加Redis 根据经纬度实现附近的人查询功能

本文介绍如何使用 PHP 和 Redis 的 Geo 功能实现地理定位服务。通过存储用户经纬度信息,可以快速查询指定坐标附近的用户,并按距离排序。文章提供了完整的代码示例及 Redis 存储格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、业务需求:用户信息存储经纬度,根据某个经纬度查询附近的人,已圆为中心,可根据距离从近到远排序。

2、使用技术:php,redis geo(geoadd,georadius),存储格式为:zset(有序集合)

3、相关文档:http://redisdoc.com/geo/georadius.html

实现:

<?php
/**
 * @author
 * @since
 */
header("Content-type: text/html; charset=utf-8"); //编码
ini_set('date.timezone', 'Asia/Shanghai');  //定义时间地点
ini_set('memory_limit', '2024M'); //扩展php内存

class statistics
{
    protected $redis;

    public function __construct()
    {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    public function index()
    {
        $total = 500000; //总数

        //模拟生成坐标,循环写入
        for ($i = 0; $i < $total; $i++) {

            //有效的经度介于 -180 度至 180 度之间。
            //有效的纬度介于 -85.05112878 度至 85.05112878 度之间。

            $num      = $this->randomFloat(-85, 85);
            $latitude = sprintf("%.6f", $num); //维度

            $num       = $this->randomFloat(-180, 180);
            $longitude = sprintf("%.6f", $num); //经度

            $this->redis->rawCommand('geoadd', 'user_info', $longitude, $latitude, 'user_id_' . $i);
        }

        echo '>>>>>' . date('Y-m-d H:i:s', time()) . '>>>>>';

    }

    function randomFloat($min = 0, $max = 1)
    {
        return $min + mt_rand() / mt_getrandmax() * ($max - $min);
    }

    public function __destruct()
    {
        $cx = '39.90'; //纬度
        $cy = '116.40'; //经度

        //获取本经纬度坐标100km内容的信息并根据距离从近到远排序显示5条
        $rediss = $this->redis->rawCommand('georadius', 'user_info', $cy, $cx, '100', 'km', 'WITHCOORD', 'WITHDIST', 'ASC', 'COUNT', 5);
        echo json_encode($rediss);

    }

}

$tg = new  statistics();
$tg->index();

查看数据,redis存储方式:

打印结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值