基于LBS功能应用的Geohash方案
隨著移動終端的普及,很多應(yīng)用都基于LBS功能,附近的某某(餐館、銀行、妹紙等等)。
基礎(chǔ)數(shù)據(jù)中,一般保存了目標(biāo)位置的經(jīng)緯度;利用用戶提供的經(jīng)緯度,進(jìn)行對比,從而獲得是否在附近。
目標(biāo):
查找附近的某某某,由近到遠(yuǎn)返回結(jié)果,且結(jié)果中有與目標(biāo)點(diǎn)的距離。
針對查找附近的某某某,提出兩個方案,如下:
一、方案A:
抽象為球面兩點(diǎn)距離的計算,即已知道球面上兩點(diǎn)的經(jīng)緯度;
點(diǎn)(緯度,經(jīng)度),A($radLat1,$radLng1)、B($radLat2,$radLng2);
優(yōu)點(diǎn):通俗易懂,部署簡單便捷
缺點(diǎn):每次都會查詢數(shù)據(jù)庫,性能堪憂
1、推導(dǎo)
通過余弦定理以及弧度計算方法,最終推導(dǎo)出來的算式A為:
$s = acos(cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2) + sin($radLat1) * sin($radLat2)) * $R;目前網(wǎng)上大多使用Google公開的距離計算公司,推導(dǎo)算式B為:
$s = 2*asin(sqrt(pow(sin(($radLat1-$radLat2)/2),2)+cos($radLat1)*cos($radLat2)*pow(sin(($radLng1-$radLng2)/2),2)))*$R;其中 :
$radLat1、$radLng1,$radLat2,$radLng2 為弧度
$R 為地球半徑
2、兩種算法
通過測試兩種算法,結(jié)果相同且都正確,但通過PHP代碼測試,兩點(diǎn)間距離,10W次性能對比,自行推導(dǎo)版本計算時長算式B較優(yōu),如下:
//算式A 0.56368780136108float(431) 0.57460689544678float(431) 0.59051203727722float(431)//算式B 0.47404885292053float(431) 0.47808718681335float(431) 0.47946381568909float(431)3、所以采用數(shù)學(xué)方法推導(dǎo)出的公式:
<?php//根據(jù)經(jīng)緯度計算距離 其中A($lat1,$lng1)、B($lat2,$lng2)public static function getDistance($lat1,$lng1,$lat2,$lng2) {//地球半徑$R = 6378137;//將角度轉(zhuǎn)為狐度$radLat1 = deg2rad($lat1);$radLat2 = deg2rad($lat2);$radLng1 = deg2rad($lng1);$radLng2 = deg2rad($lng2);//結(jié)果$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;//精度$s = round($s* 10000)/10000;return round($s);} ?>4、實際應(yīng)用中
在實際應(yīng)用中,需要從數(shù)據(jù)庫中遍歷取出符合條件,以及排序等操作,將所有數(shù)據(jù)取出,然后通過PHP循環(huán)對比,篩選符合條件結(jié)果,顯然性能低下;所以我們利用下Mysql存儲函數(shù)來解決這個問題吧。
1)、創(chuàng)建MySQL存儲函數(shù),并對經(jīng)緯度字段建立索引
DELIMITER $$ CREATE DEFINER=`root`@`%` FUNCTION `GETDISTANCE`(lat1 DOUBLE, lng1 DOUBLE, lat2 DOUBLE, lng2 DOUBLE) RETURNS double READS SQL DATA DETERMINISTIC BEGIN DECLARE RAD DOUBLE; DECLARE EARTH_RADIUS DOUBLE DEFAULT 6378137; DECLARE radLat1 DOUBLE; DECLARE radLat2 DOUBLE; DECLARE radLng1 DOUBLE; DECLARE radLng2 DOUBLE; DECLARE s DOUBLE; SET RAD = PI() / 180.0; SET radLat1 = lat1 * RAD; SET radLat2 = lat2 * RAD; SET radLng1 = lng1 * RAD; SET radLng2 = lng2 * RAD; SET s = ACOS(COS(radLat1)*COS(radLat2)*COS(radLng1-radLng2)+SIN(radLat1)*SIN(radLat2))*EARTH_RADIUS; SET s = ROUND(s * 10000) / 10000; RETURN s; END$$ DELIMITER ;2)、查詢SQL
通過SQL,可設(shè)置距離以及排序;可搜索出符合條件的信息,以及有一個較好的排序
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算法是一種地址編碼,它能把二維的經(jīng)緯度編碼成一維的字符串。比如,成都永豐立交的編碼是wm3yr31d2524
優(yōu)點(diǎn):
1)、利用一個字段,即可存儲經(jīng)緯度;搜索時,只需一條索引,效率較高
2)、編碼的前綴可以表示更大的區(qū)域,查找附近的,非常方便。 SQL中,LIKE 'wm3yr3%',即可查詢附近的所有地點(diǎn)。
3)、通過編碼精度可模糊坐標(biāo)、隱私保護(hù)等。
缺點(diǎn):?
距離和排序需二次運(yùn)算(篩選結(jié)果中運(yùn)行,其實挺快)
1、geohash的編碼算法
成都永豐立交經(jīng)緯度(30.63578,104.031601)
1)、緯度范圍(-90, 90)平分成兩個區(qū)間(-90, 0)、(0, 90), 如果目標(biāo)緯度位于前一個區(qū)間,則編碼為0,否則編碼為1。
由于30.625265屬于(0, 90),所以取編碼為1。
然后再將(0, 90)分成 (0, 45), (45, 90)兩個區(qū)間,而39.92324位于(0, 45),所以編碼為0
然后再將(0, 45)分成 (0, 22.5), (22.5, 45)兩個區(qū)間,而39.92324位于(22.5, 45),所以編碼為1
依次類推可得永豐立交緯度編碼為101010111001001000100101101010。
2)、經(jīng)度也用同樣的算法,對(-180, 180)依次細(xì)分,(-180,0)、(0,180) 得出編碼110010011111101001100000000000
3)、合并經(jīng)緯度編碼,從高到低,先取一位經(jīng)度,再取一位緯度;得出結(jié)果 111001001100011111101011100011000010110000010001010001000100
4)、用0-9、b-z(去掉a, i, l, o)這32個字母進(jìn)行base32編碼,得到(30.63578,104.031601)的編碼為wm3yr31d2524。
11100 10011 00011 11110 10111 00011 00001 01100 00010 00101 00010 00100 => wm3yr31d2524十進(jìn)制 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 十進(jìn)制 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 z2、策略
1)、在緯度和經(jīng)度入庫時,數(shù)據(jù)庫新加一字段geohash,記錄此點(diǎn)的geohash值
2)、查找附近,利用 在SQL中 LIKE 'wm3yr3%';且此結(jié)果可緩存;在小區(qū)域內(nèi),不會因為改變經(jīng)緯度,而重新數(shù)據(jù)庫查詢
3)、查找出的有限結(jié)果,如需要求距離或者排序,可利用距離公式和二維數(shù)據(jù)排序;此時也是少量數(shù)據(jù),會很快的。
3、一個PHP基類
geohash.class.php
<?php /** * Encode and decode geohashes */ class Geohash {private $coding = "0123456789bcdefghjkmnpqrstuvwxyz";private $codingMap = array();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);}}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);$long = $this->binDecode($blong, -180, 180);$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);}public function encode($lat,$long) {$plat = $this->precision($lat);$latbits = 1;$err = 45;while($err > $plat) {$latbits++;$err/ = 2;}$plong = $this->precision($long);$longbits = 1;$err = 90;while($err > $plong) {$longbits++;$err /= 2;}$bits = max($latbits,$longbits);$longbits = $bits;$latbits = $bits;$addlong = 1;while (($longbits+$latbits) % 5 != 0) {$longbits += $addlong;$latbits += !$addlong;$addlong = !$addlong;}$blat = $this->binEncode($lat, -90, 90, $latbits);$blong = $this->binEncode($long, -180, 180, $longbits);$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) {$n = bindec(substr($binary, $i, 5));$hash = $hash . $this->coding[$n];}return $hash;}private function calcError($bits, $min, $max) {$err = ($max - $min) / 2;while ($bits--) {$err /= 2;}return $err;}private function precision($number) {$precision = 0;$pt = strpos($number,'.');if ($pt! == false) {$precision = -(strlen($number) - $pt - 1);}return pow(10, $precision) / 2;}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);}}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);}} } ?>三、測試
<?php require_once('Mysql.class.php'); require_once('geohash.class.php'); //mysql $conf = array('host' = > '127.0.0.1','port' = > 3306,'user' = > 'root','password' = > '123456','database' = > 'mocube','charset' = > 'utf8','persistent' = > false );$mysql = new Db_Mysql($conf); $geohash = new Geohash;//經(jīng)緯度轉(zhuǎn)換成Geohash $sql = 'select shop_id,latitude,longitude from mb_shop_ext'; $data = $mysql->queryAll($sql); foreach($data as $val) {$geohash_val = $geohash->encode($val['latitude'],$val['longitude']);$sql = 'update mb_shop_ext set geohash = "'.$geohash_val.'" where shop_id = '.$val['shop_id'];echo $sql;$re = $mysql->query($sql);var_dump($re); } //獲取附近的信息 $n_latitude = $_GET['la']; $n_longitude = $_GET['lo']; //開始 $b_time = microtime(true);//方案A,直接利用數(shù)據(jù)庫存儲函數(shù),遍歷排序 $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'; $data = $mysql->queryAll($sql); //結(jié)束 $e_time = microtime(true); echo $e_time - $b_time; var_dump($data); exit;//方案B geohash求出附近,然后排序 //當(dāng)前 geohash值 $n_geohash = $geohash->encode($n_latitude,$n_longitude); //附近,參數(shù)n代表Geohash,精確的位數(shù),也就是大概距離;n=6時候,大概為附近1千米 $n = $_GET['n']; $like_geohash = substr($n_geohash, 0, $n); $sql = 'select * from mb_shop_ext where geohash like "'.$like_geohash.'%"'; echo $sql; $data = $mysql->queryAll($sql); //算出實際距離 foreach($data as $key =>$val) {$distance = getDistance($n_latitude, $n_longitude, $val['latitude'], $val['longitude']);$data[$key]['distance'] = $distance;//排序列$sortdistance[$key] = $distance; } //距離排序 array_multisort($sortdistance,SORT_ASC,$data); //結(jié)束 $e_time = microtime(true); echo $e_time - $b_time; var_dump($data); //根據(jù)經(jīng)緯度計算距離 其中A($lat1,$lng1)、B($lat2,$lng2) function getDistance($lat1, $lng1, $lat2, $lng2) {//地球半徑$R = 6378137;//將角度轉(zhuǎn)為狐度$radLat1 = deg2rad($lat1);$radLat2 = deg2rad($lat2);$radLng1 = deg2rad($lng1);$radLng2 = deg2rad($lng2);//結(jié)果$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;//精度$s = round($s* 10000)/10000;return round($s); } ?>四、總結(jié)
方案B的亮點(diǎn)在于:
1、搜索結(jié)果可緩存,重復(fù)使用,不會因為用戶有小范圍的移動,直接穿透數(shù)據(jù)庫查詢。
2、先縮小結(jié)果范圍,再運(yùn)算、排序,可提升性能。
254條記錄,性能對比,在實際應(yīng)用場景中,方案B數(shù)據(jù)庫搜索可內(nèi)存緩存;且如數(shù)據(jù)量更大,方案B結(jié)果會更優(yōu)。
方案A: 0.016560077667236 0.032402992248535 0.040318012237549方案B 0.0079810619354248 0.0079669952392578 0.0064868927001953兩種方案,根據(jù)應(yīng)用場景以及負(fù)載情況合理選擇,當(dāng)然推薦方案B。
不管哪種方案,都記得,給列加上索引,利于數(shù)據(jù)庫檢索。
注意:在數(shù)據(jù)庫中給Geohash加上索引,用戶位置頻繁發(fā)生改變則會導(dǎo)致索引重建,這勢必會給數(shù)據(jù)庫造成很大的壓力
可換一種方案:使用Redis來實現(xiàn)LBS的應(yīng)用
轉(zhuǎn)載:查找附近的xxx 球面距離以及Geohash方案探討
總結(jié)
以上是生活随笔為你收集整理的基于LBS功能应用的Geohash方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于LBS的地理位置附近的搜索以及由近及
- 下一篇: LBS定位应用app的兴趣点与名称搜索