LBS经纬度编码搜索实现


LBS经纬度编码搜索实现


正文

在纬度相等的情况下:

  • 经度每隔0.00001度,距离相差约1米;
  • 每隔0.0001度,距离相差约10米;
  • 每隔0.001度,距离相差约100米;
  • 每隔0.01度,距离相差约1000米;
  • 每隔0.1度,距离相差约10000米。

在经度相等的情况下:

  • 纬度每隔0.00001度,距离相差约1.1米;
  • 每隔0.0001度,距离相差约11米;
  • 每隔0.001度,距离相差约111米;
  • 每隔0.01度,距离相差约1113米;
  • 每隔0.1度,距离相差约11132米。

引导

geohash的编码算法

成都永丰立交经纬度(30.63578,104.031601)

1)、纬度范围(-90, 90)平分成两个区间(-90, 0)、(0, 90), 如果目标纬度位于前一个区间,则编码为0,否则编码为1。

由于30.625265属于(0, 90),所以取编码为1。

然后再将(0, 90)分成 (0, 45), (45, 90)两个区间,而39.92324位于(0, 45),所以编码为0

然后再将(0, 45)分成 (0, 22.5), (22.5, 45)两个区间,而39.92324位于(22.5, 45),所以编码为1

依次类推可得永丰立交纬度编码为101010111001001000100101101010

2)、经度也用同样的算法,对(-180, 180)依次细分,(-180,0)、(0,180) 得出编码110010011111101001100000000000

3)、合并经纬度编码,从高到低,先取一位经度,再取一位纬度;得出结果 111001001100011111101011100011000010110000010001010001000100

4)、用0-9、a-z(去掉a, i, l, o)这36个字母进行base32编码,得到(30.63578,104.031601)的编码为 wm3yr31d2524。

11100 10011 00011 11110 10111 00011 00001 01100 00010 00101 00010 00100 => wm3yr31d2524

十进制    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
base32   0   1   2   3   4   5   6   7   8   9   b   c   d   e   f   g
十进制  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31
base32   h   j   k   m   n   p   q   r   s   t   u   v   w   x   y   z

Geohash算法 PHP实现

geohash.class.php

<?php
/**
* Encode and decode geohashes
*/
class Geohash
{
    private $coding = "0123456789bcdefghjkmnpqrstuvwxyz";
    private $codingMap = array();

    /**
     * Geohash constructor.
     * $codingMap 数组对应组建,如 $this->codingMap['0'] = '00000',$this->codingMap['b'] = '01010'
     */
    public function Geohash()
    {
        for ($i = 0; $i < 32; $i++) {
            $this->codingMap[substr($this->coding, $i, 1)] = str_pad(decbin($i), 5, "0", STR_PAD_LEFT);
        }
    }

    /**
     * 把经纬度格式化为一个字符串
     * @param $lat 维度
     * @param $long 经度
     * @return string
     */
    public function encode($lat, $long)
    {
        // 维度一直运算到精度以下,如 $plat = 0.1,则维度位数 $latbits = 9
        $plat = $this->precision($lat);
        $latbits = 1;
        $err = 45;
        while ($err > $plat) {
            $latbits++;
            $err /= 2;
        }

        // 经度一直运算到精度以下,如 $plong = 0.1,则经度位数 $longbits = 10
        $plong = $this->precision($long);
        $longbits = 1;
        $err = 90;
        while ($err > $plong) {
            $longbits++;
            $err /= 2;
        }

        // 计算经纬度精度值
        $bits = max($latbits, $longbits);  // 经纬度精度中取最大位数
        $longbits = $bits;
        $latbits = $bits;
        $addlong = 1;  // $addlong 在 1 和 0 间 变动,第一轮经度位数长度加1,第二轮维度位数长度加1,以此类推
        while (($longbits + $latbits) % 5 != 0) {  // 直到经纬度位数长度之和被5整除,32位中以5位为1个单位,如 1 为 00001
            $longbits += $addlong;
            $latbits += !$addlong;
            $addlong = !$addlong;
        }

        $blat = $this->binEncode($lat, -90, 90, $latbits);  // 获取维度二进制字符串,如 101010111001001000100101101010
        $blong = $this->binEncode($long, -180, 180, $longbits);  // 获取经度二进制字符串,如 110010011111101001100000000000

        // 循环组装经纬度混合的二进制字符串
        $binary = "";
        $uselong = 1;  // 是否使用经度
        while (strlen($blat) + strlen($blong)) {
            if ($uselong) {
                $binary = $binary . substr($blong, 0, 1);
                $blong = substr($blong, 1);
            } else {
                $binary = $binary . substr($blat, 0, 1);
                $blat = substr($blat, 1);
            }

            $uselong = !$uselong;
        }

        // 组装字符串
        $hash = "";
        for ($i = 0; $i < strlen($binary); $i += 5) {  // 循环,每次5位长度,2进制转为10进制,拼接字符串
            $n = bindec(substr($binary, $i, 5));
            $hash = $hash . $this->coding[$n];
        }

        return $hash;
    }

    /**
     * 返回一个数的精度,如 10.01,返回 0.005
     * @param $number
     * @return float|int
     */
    private function precision($number)
    {
        $precision = 0;
        $pt = strpos($number, '.');
        if ($pt !== false) {
            $precision = -(strlen($number) - $pt - 1);
        }
        return pow(10, $precision) / 2;
    }

    /**
     * 通过递归转化为二进制,以 $bitcount 为维度
     * @param $number  浮点数字,如 12.345
     * @param $min  最小值,如 0
     * @param $max  最大值,如 90
     * @param $bitcount  精度,如 10
     * @return string,返回字符串,如 101010111001001000100101101010
     */
    private function binEncode($number, $min, $max, $bitcount)
    {
        if ($bitcount == 0) {
            return "";
        }

        $mid = ($min + $max) / 2;
        if ($number > $mid) {  // 浮点数大于平均值,说明在上面区间,否则在下面区间
            return "1" . $this->binEncode($number, $mid, $max, $bitcount - 1);
        } else {
            return "0" . $this->binEncode($number, $min, $mid, $bitcount - 1);
        }
    }

    /**
     * 把字符串还原为经纬度
     * @param $hash
     * @return array
     */
    public function decode($hash)
    {
        $binary = "";
        $hl = strlen($hash);
        for ($i = 0; $i < $hl; $i++) {
            $binary .= $this->codingMap[substr($hash, $i, 1)];
        }

        $bl = strlen($binary);
        $blat = "";  // 维度二进制字符串
        $blong = "";  // 经度二进制字符串
        for ($i = 0; $i < $bl; $i++) {
            if ($i % 2) {
                $blat = $blat . substr($binary, $i, 1);
            } else {
                $blong = $blong . substr($binary, $i, 1);
            }
        }

        $lat = $this->binDecode($blat, -90, 90);  // 如 22.53332041204
        $long = $this->binDecode($blong, -180, 180);  // 如 113.93041066825

        $latErr = $this->calcError(strlen($blat), -90, 90);
        $longErr = $this->calcError(strlen($blong), -180, 180);

        $latPlaces = max(1, -round(log10($latErr))) - 1;
        $longPlaces = max(1, -round(log10($longErr))) - 1;

        $lat = round($lat, $latPlaces);
        $long = round($long, $longPlaces);

        return array($lat, $long);
    }

    /**
     * 通过二进值数计算出最小值与最大值中所处的位置浮点数
     * @param $binary  二进制字符串
     * @param $min  最小值
     * @param $max  最大值
     * @return float|int  浮点数
     */
    private function binDecode($binary, $min, $max)
    {
        $mid = ($min + $max) / 2;

        if (strlen($binary) == 0) {
            return $mid;
        }

        $bit = substr($binary, 0, 1);
        $binary = substr($binary, 1);

        if ($bit == 1) {
            return $this->binDecode($binary, $mid, $max);
        } else {
            return $this->binDecode($binary, $min, $mid);
        }
    }

    /**
     * 计算误差
     * @param $bits  字符长度
     * @param $min
     * @param $max
     * @return float|int  返回误差范围
     */
    private function calcError($bits, $min, $max)
    {
        $err = ($max - $min) / 2;  // 最大值减最小值后再求平均值,如 $min = -90,$max = 90,则 $err = 90
        while ($bits--) {  // 每次字符长度减1,直到等于0,如 为 26、25、24、23  等
            $err /= 2;  // 每次平均值除以2,如为 45、22.5、11.25、5.625 等
        }

        return $err;   // 如 6.7055225372314E-7
    }
}

使用:

<?php
require_once('geohash.class.php');

$longitude = 113.93041;  // 经度
$latitude = 22.53332;  // 维度

$geohash = new Geohash;
$geohash_val = $geohash->encode($latitude, $longitude);  // 输出 ws100w1d4gr

//附近,参数n代表Geohash,精确的位数,也就是大概距离;n=6时候,大概为附近1千米
$n = 6;
$like_geohash = substr($geohash_val, 0, $n);

解说

Geohash::Geohash() 进行$codingMap的初始化:

Array
(
    [0] => 00000
    [1] => 00001
    [2] => 00010
    [3] => 00011
    [4] => 00100
    [5] => 00101
    [6] => 00110
    [7] => 00111
    [8] => 01000
    [9] => 01001
    [b] => 01010
    [c] => 01011
    [d] => 01100
    [e] => 01101
    [f] => 01110
    [g] => 01111
    [h] => 10000
    [j] => 10001
    [k] => 10010
    [m] => 10011
    [n] => 10100
    [p] => 10101
    [q] => 10110
    [r] => 10111
    [s] => 11000
    [t] => 11001
    [u] => 11010
    [v] => 11011
    [w] => 11100
    [x] => 11101
    [y] => 11110
    [z] => 11111
)

Geohash::precision() 对一个数字进行精度评估,如 22.53 返回 0.005, 22.53332 返回 5.0E-6。

函数原型

pow() 返回一个数指数运算后的值,如pow(10, 2) 返回 100、pow(10, -2) 返回 0.01、pow(10, -5) 返回 1.0E-5、 pow(2, 10) 返回 1024、 pow(2, -2) 返回 0.25,原型:

/**
 * 指数表达式
 * Exponential expression
 * @link https://php.net/manual/en/function.pow.php
 * @param int|float $num <p>
 * The base to use
 * </p>
 * @param int|float $exponent <p>
 * The exponent
 * </p>
 * @return int|float base raised to the power of exp.
 * If the result can be represented as integer it will be returned as type
 * integer, else it will be returned as type float.
 * If the power cannot be computed false will be returned instead.
 */
#[Pure]
function pow ($num, $exponent) {}

bindec()二进制数转化为十进制,如 bindec(1010) 返回 10,原型:

/**
 * Binary to decimal
 * @link https://php.net/manual/en/function.bindec.php
 * @param string $binary_string <p>
 * The binary string to convert
 * </p>
 * @return int|float The decimal value of binary_string
 */
#[Pure]
function bindec ($binary_string) {}

round() 函数对浮点数进行四舍五入,默认小数位为0,原型:

/**
 * Returns the rounded value of val to specified precision (number of digits after the decimal point).
 * precision can also be negative or zero (default).
 * Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.
 * @link https://php.net/manual/en/function.round.php
 * @param float $num <p>
 * The value to round
 * </p>
 * @param int $precision [optional] <p>
 * The optional number of decimal digits to round to.
 * </p>
 * @param int $mode [optional] <p>
 * One of PHP_ROUND_HALF_UP,
 * PHP_ROUND_HALF_DOWN,
 * PHP_ROUND_HALF_EVEN, or
 * PHP_ROUND_HALF_ODD.
 * </p>
 * @return float The rounded value
 */
#[Pure]
function round ($num, $precision = 0, $mode = PHP_ROUND_HALF_UP) {}
/**
 * Natural logarithm
 * @link https://php.net/manual/en/function.log.php
 * @param float $num <p>
 * The value to calculate the logarithm for
 * </p>
 * @param float $base [optional] <p>
 * The optional logarithmic base to use
 * (defaults to 'e' and so to the natural logarithm).
 * </p>
 * @return float The logarithm of arg to
 * base, if given, or the
 * natural logarithm.
 */
#[Pure]
function log ($num, $base = null) {}
/**
 * Base-10 logarithm
 * @link https://php.net/manual/en/function.log10.php
 * @param float $num <p>
 * The argument to process
 * </p>
 * @return float The base-10 logarithm of arg
 */
#[Pure]
function log10 ($num) {}






参考资料

geohash实现距离排序算法php https://blog.csdn.net/littlexiaoshuishui/article/details/88950064

LBS:附近搜索(geohash算法:经纬度编码搜索) Django http://www.360doc.com/content/14/0714/20/16044571_394404568.shtml

Geohash精度和原理 https://www.cnblogs.com/feiquan/p/11380461.html


返回