目录结构

随着移动终端的普及,很多应用都基于LBS功能,附近的某某(餐馆、银行、妹纸等等)。
基础数据中,一般保存了目标位置的经纬度;利用用户提供的经纬度,进行对比,从而获得是否在附近。
目标:
查找附近的某某某,由近到远返回结果,且结果中有与目标点的距离。
针对查找附近的某某某,提出两个方案,如下:

一、方案A:

1、推导

通过余弦定理以及弧度计算方法,最终推导出来的算式A为:
$s = acos(cos($radLat1) cos($radLat2) cos($radLng1 - $radLng2) + sin($radLat1) sin($radLat2)) $R;
目前网上大多使用Google公开的距离计算公司,推导算式B为:
$s = 2asin(sqrt(pow(sin(($radLat1-$radLat2)/2),2)+cos($radLat1)cos($radLat2)pow(sin(($radLng1-$radLng2)/2),2)))$R;
其中 :
$radLat1、$radLng1,$radLat2,$radLng2 为弧度
$R 为地球半径

2、两种算法

通过测试两种算法,结果相同且都正确,但通过PHP代码测试,两点间距离,10W次性能对比,自行推导版本计算时长算式B较优,如下:
//算式A
0.56368780136108float(431)
0.57460689544678float(431)
0.59051203727722float(431)

//算式B
0.47404885292053float(431)
0.47808718681335float(431)
0.47946381568909float(431)

3、所以采用数学方法推导出的公式:

  1. <?php
  2. //根据经纬度计算距离 其中A($lat1,$lng1)、B($lat2,$lng2)
  3. public static function getDistance($lat1,$lng1,$lat2,$lng2) {
  4. //地球半径
  5. $R = 6378137;
  6. //将角度转为狐度
  7. $radLat1 = deg2rad($lat1);
  8. $radLat2 = deg2rad($lat2);
  9. $radLng1 = deg2rad($lng1);
  10. $radLng2 = deg2rad($lng2);
  11. //结果
  12. $s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
  13. //精度
  14. $s = round($s* 10000)/10000;
  15. return round($s);
  16. }
  17. ?>

4、实际应用中

在实际应用中,需要从数据库中遍历取出符合条件,以及排序等操作,将所有数据取出,然后通过PHP循环对比,筛选符合条件结果,显然性能低下;所以我们利用下Mysql存储函数来解决这个问题吧。

1)、创建MySQL存储函数,并对经纬度字段建立索引

  1. DELIMITER $$
  2. CREATE DEFINER=`root`@`%` FUNCTION `GETDISTANCE`(lat1 DOUBLE, lng1 DOUBLE, lat2 DOUBLE, lng2 DOUBLE) RETURNS double
  3. READS SQL DATA
  4. DETERMINISTIC
  5. BEGIN
  6. DECLARE RAD DOUBLE;
  7. DECLARE EARTH_RADIUS DOUBLE DEFAULT 6378137;
  8. DECLARE radLat1 DOUBLE;
  9. DECLARE radLat2 DOUBLE;
  10. DECLARE radLng1 DOUBLE;
  11. DECLARE radLng2 DOUBLE;
  12. DECLARE s DOUBLE;
  13. SET RAD = PI() / 180.0;
  14. SET radLat1 = lat1 * RAD;
  15. SET radLat2 = lat2 * RAD;
  16. SET radLng1 = lng1 * RAD;
  17. SET radLng2 = lng2 * RAD;
  18. SET s = ACOS(COS(radLat1)*COS(radLat2)*COS(radLng1-radLng2)+SIN(radLat1)*SIN(radLat2))*EARTH_RADIUS;
  19. SET s = ROUND(s * 10000) / 10000;
  20. RETURN s;
  21. END$$
  22. DELIMITER ;

2)、查询SQL

通过SQL,可设置距离以及排序;可搜索出符合条件的信息,以及有一个较好的排序

  1. SELECT *,latitude,longitude,GETDISTANCE(latitude,longitude,30.663262,104.071619) AS distance FROM mb_shop_ext where 1 HAVING distance<1000 ORDER BY distance ASC LIMIT 0,10


二、方案B:Geohash算法

Geohash算法是一种地址编码,它能把二维的经纬度编码成一维的字符串。比如,成都永丰立交的编码是wm3yr31d2524

优点:

1)、利用一个字段,即可存储经纬度;搜索时,只需一条索引,效率较高
2)、编码的前缀可以表示更大的区域,查找附近的,非常方便。 SQL中,LIKE ‘wm3yr3%’,即可查询附近的所有地点。
3)、通过编码精度可模糊坐标、隐私保护等。

缺点:

距离和排序需二次运算(筛选结果中运行,其实挺快)

1、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、b-z(去掉a, i, l, o)这32个字母进行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

2、策略

1)、在纬度和经度入库时,数据库新加一字段geohash,记录此点的geohash值
2)、查找附近,利用 在SQL中 LIKE ‘wm3yr3%’;且此结果可缓存;在小区域内,不会因为改变经纬度,而重新数据库查询
3)、查找出的有限结果,如需要求距离或者排序,可利用距离公式和二维数据排序;此时也是少量数据,会很快的。

3、一个PHP基类

geohash.class.php

  1. <?php
  2. /**
  3. * Geohash generation class
  4. * http://blog.dixo.net/downloads/
  5. *
  6. * This file copyright (C) 2008 Paul Dixon (paul@elphin.com)
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version 3
  11. * of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  21. */
  22. /**
  23. * Encode and decode geohashes
  24. *
  25. */
  26. class Geohash
  27. {
  28. private $coding="0123456789bcdefghjkmnpqrstuvwxyz";
  29. private $codingMap=array();
  30. public function Geohash()
  31. {
  32. //build map from encoding char to 0 padded bitfield
  33. for($i=0; $i<32; $i++)
  34. {
  35. $this->codingMap[substr($this->coding,$i,1)]=str_pad(decbin($i), 5, "0", STR_PAD_LEFT);
  36. }
  37. }
  38. /**
  39. * Decode a geohash and return an array with decimal lat,long in it
  40. */
  41. public function decode($hash)
  42. {
  43. //decode hash into binary string
  44. $binary="";
  45. $hl=strlen($hash);
  46. for($i=0; $i<$hl; $i++)
  47. {
  48. $binary.=$this->codingMap[substr($hash,$i,1)];
  49. }
  50. //split the binary into lat and log binary strings
  51. $bl=strlen($binary);
  52. $blat="";
  53. $blong="";
  54. for ($i=0; $i<$bl; $i++)
  55. {
  56. if ($i%2)
  57. $blat=$blat.substr($binary,$i,1);
  58. else
  59. $blong=$blong.substr($binary,$i,1);
  60. }
  61. //now concert to decimal
  62. $lat=$this->binDecode($blat,-90,90);
  63. $long=$this->binDecode($blong,-180,180);
  64. //figure out how precise the bit count makes this calculation
  65. $latErr=$this->calcError(strlen($blat),-90,90);
  66. $longErr=$this->calcError(strlen($blong),-180,180);
  67. //how many decimal places should we use? There's a little art to
  68. //this to ensure I get the same roundings as geohash.org
  69. $latPlaces=max(1, -round(log10($latErr))) - 1;
  70. $longPlaces=max(1, -round(log10($longErr))) - 1;
  71. //round it
  72. $lat=round($lat, $latPlaces);
  73. $long=round($long, $longPlaces);
  74. return array($lat,$long);
  75. }
  76. /**
  77. * Encode a hash from given lat and long
  78. */
  79. public function encode($lat,$long)
  80. {
  81. //how many bits does latitude need?
  82. $plat=$this->precision($lat);
  83. $latbits=1;
  84. $err=45;
  85. while($err>$plat)
  86. {
  87. $latbits++;
  88. $err/=2;
  89. }
  90. //how many bits does longitude need?
  91. $plong=$this->precision($long);
  92. $longbits=1;
  93. $err=90;
  94. while($err>$plong)
  95. {
  96. $longbits++;
  97. $err/=2;
  98. }
  99. //bit counts need to be equal
  100. $bits=max($latbits,$longbits);
  101. //as the hash create bits in groups of 5, lets not
  102. //waste any bits - lets bulk it up to a multiple of 5
  103. //and favour the longitude for any odd bits
  104. $longbits=$bits;
  105. $latbits=$bits;
  106. $addlong=1;
  107. while (($longbits+$latbits)%5 != 0)
  108. {
  109. $longbits+=$addlong;
  110. $latbits+=!$addlong;
  111. $addlong=!$addlong;
  112. }
  113. //encode each as binary string
  114. $blat=$this->binEncode($lat,-90,90, $latbits);
  115. $blong=$this->binEncode($long,-180,180,$longbits);
  116. //merge lat and long together
  117. $binary="";
  118. $uselong=1;
  119. while (strlen($blat)+strlen($blong))
  120. {
  121. if ($uselong)
  122. {
  123. $binary=$binary.substr($blong,0,1);
  124. $blong=substr($blong,1);
  125. }
  126. else
  127. {
  128. $binary=$binary.substr($blat,0,1);
  129. $blat=substr($blat,1);
  130. }
  131. $uselong=!$uselong;
  132. }
  133. //convert binary string to hash
  134. $hash="";
  135. for ($i=0; $i<strlen($binary); $i+=5)
  136. {
  137. $n=bindec(substr($binary,$i,5));
  138. $hash=$hash.$this->coding[$n];
  139. }
  140. return $hash;
  141. }
  142. /**
  143. * What's the maximum error for $bits bits covering a range $min to $max
  144. */
  145. private function calcError($bits,$min,$max)
  146. {
  147. $err=($max-$min)/2;
  148. while ($bits--)
  149. $err/=2;
  150. return $err;
  151. }
  152. /*
  153. * returns precision of number
  154. * precision of 42 is 0.5
  155. * precision of 42.4 is 0.05
  156. * precision of 42.41 is 0.005 etc
  157. */
  158. private function precision($number)
  159. {
  160. $precision=0;
  161. $pt=strpos($number,'.');
  162. if ($pt!==false)
  163. {
  164. $precision=-(strlen($number)-$pt-1);
  165. }
  166. return pow(10,$precision)/2;
  167. }
  168. /**
  169. * create binary encoding of number as detailed in http://en.wikipedia.org/wiki/Geohash#Example
  170. * removing the tail recursion is left an exercise for the reader
  171. */
  172. private function binEncode($number, $min, $max, $bitcount)
  173. {
  174. if ($bitcount==0)
  175. return "";
  176. #echo "$bitcount: $min $max<br>";
  177. //this is our mid point - we will produce a bit to say
  178. //whether $number is above or below this mid point
  179. $mid=($min+$max)/2;
  180. if ($number>$mid)
  181. return "1".$this->binEncode($number, $mid, $max,$bitcount-1);
  182. else
  183. return "0".$this->binEncode($number, $min, $mid,$bitcount-1);
  184. }
  185. /**
  186. * decodes binary encoding of number as detailed in http://en.wikipedia.org/wiki/Geohash#Example
  187. * removing the tail recursion is left an exercise for the reader
  188. */
  189. private function binDecode($binary, $min, $max)
  190. {
  191. $mid=($min+$max)/2;
  192. if (strlen($binary)==0)
  193. return $mid;
  194. $bit=substr($binary,0,1);
  195. $binary=substr($binary,1);
  196. if ($bit==1)
  197. return $this->binDecode($binary, $mid, $max);
  198. else
  199. return $this->binDecode($binary, $min, $mid);
  200. }
  201. }

Geohash距离估算

一、经纬度距离换算

a)在纬度相等的情况下:
经度每隔0.00001度,距离相差约1米;
每隔0.0001度,距离相差约10米;
每隔0.001度,距离相差约100米;
每隔0.01度,距离相差约1000米;
每隔0.1度,距离相差约10000米。
b)在经度相等的情况下:
纬度每隔0.00001度,距离相差约1.1米;
每隔0.0001度,距离相差约11米;
每隔0.001度,距离相差约111米;
每隔0.01度,距离相差约1113米;
每隔0.1度,距离相差约11132米。

二、Geohash距离换算(使用base32编码)

如果geohash的位数是9位数的时候,大概为附近2米

geohash length lat bits lng bits lat error lng error km error
1 2 3 ±23 ±23 ±2500
2 5 5 ± 2.8 ± 5.6 ±630
3 7 8 ± 0.70 ± 0.7 ±78
4 10 10 ± 0.087 ± 0.18 ±20
5 12 13 ± 0.022 ± 0.022 ±2.4
6 15 15 ± 0.0027 ± 0.0055 ±0.61
7 17 18 ±0.00068 ±0.00068 ±0.076
8 20 20 ±0.000085 ±0.00017 ±0.019

image.png

三、测试

  1. <?php
  2. require_once('Mysql.class.php');
  3. require_once('geohash.class.php');
  4. //mysql
  5. $conf = array(
  6. 'host' = > '127.0.0.1',
  7. 'port' = > 3306,
  8. 'user' = > 'root',
  9. 'password' = > '123456',
  10. 'database' = > 'mocube',
  11. 'charset' = > 'utf8',
  12. 'persistent' = > false
  13. );
  14. $mysql = new Db_Mysql($conf);
  15. $geohash = new Geohash;
  16. //经纬度转换成Geohash
  17. $sql = 'select shop_id,latitude,longitude from mb_shop_ext';
  18. $data = $mysql->queryAll($sql);
  19. foreach($data as $val) {
  20. $geohash_val = $geohash->encode($val['latitude'],$val['longitude']);
  21. $sql = 'update mb_shop_ext set geohash = "'.$geohash_val.'" where shop_id = '.$val['shop_id'];
  22. echo $sql;
  23. $re = $mysql->query($sql);
  24. var_dump($re);
  25. }
  26. //获取附近的信息
  27. $n_latitude = $_GET['la'];
  28. $n_longitude = $_GET['lo'];
  29. //开始
  30. $b_time = microtime(true);
  31. //方案A,直接利用数据库存储函数,遍历排序
  32. $sql = 'SELECT *,latitude,longitude,GETDISTANCE(latitude,longitude,'.$n_latitude.','.$n_longitude.') AS distance FROM mb_shop_ext where 1 HAVING distance<1000 ORDER BY distance ASC';
  33. $data = $mysql->queryAll($sql);
  34. //结束
  35. $e_time = microtime(true);
  36. echo $e_time - $b_time;
  37. var_dump($data);
  38. exit;
  39. //方案B geohash求出附近,然后排序
  40. //当前 geohash值
  41. $n_geohash = $geohash->encode($n_latitude,$n_longitude);
  42. //附近,参数n代表Geohash,精确的位数,也就是大概距离;n=6时候,大概为附近1千米
  43. $n = $_GET['n'];
  44. $like_geohash = substr($n_geohash, 0, $n);
  45. $sql = 'select * from mb_shop_ext where geohash like "'.$like_geohash.'%"';
  46. echo $sql;
  47. $data = $mysql->queryAll($sql);
  48. //算出实际距离
  49. foreach($data as $key =>$val) {
  50. $distance = getDistance($n_latitude, $n_longitude, $val['latitude'], $val['longitude']);
  51. $data[$key]['distance'] = $distance;
  52. //排序列
  53. $sortdistance[$key] = $distance;
  54. }
  55. //距离排序
  56. array_multisort($sortdistance,SORT_ASC,$data);
  57. //结束
  58. $e_time = microtime(true);
  59. echo $e_time - $b_time;
  60. var_dump($data);
  61. //根据经纬度计算距离 其中A($lat1,$lng1)、B($lat2,$lng2)
  62. function getDistance($lat1, $lng1, $lat2, $lng2) {
  63. //地球半径
  64. $R = 6378137;
  65. //将角度转为狐度
  66. $radLat1 = deg2rad($lat1);
  67. $radLat2 = deg2rad($lat2);
  68. $radLng1 = deg2rad($lng1);
  69. $radLng2 = deg2rad($lng2);
  70. //结果
  71. $s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
  72. //精度
  73. $s = round($s* 10000)/10000;
  74. return round($s);
  75. }
  76. ?>

四、总结

方案B的亮点在于:
1、搜索结果可缓存,重复使用,不会因为用户有小范围的移动,直接穿透数据库查询。
2、先缩小结果范围,再运算、排序,可提升性能。
254条记录,性能对比,在实际应用场景中,方案B数据库搜索可内存缓存;且如数据量更大,方案B结果会更优。
方案A:
0.016560077667236
0.032402992248535
0.040318012237549

方案B
0.0079810619354248
0.0079669952392578
0.0064868927001953
两种方案,根据应用场景以及负载情况合理选择,当然推荐方案B。
不管哪种方案,都记得,给列加上索引,利于数据库检索。
注意:在数据库中给Geohash加上索引,用户位置频繁发生改变则会导致索引重建,这势必会给数据库造成很大的压力