這年頭和LBS相關的應用愈來愈火. 從最先的foursquare的熱鬧程度就可見通常, 如今就更不用說微信、陌陌了 (什麼, 沒聽過... 哥們, 你out 了). 和LBS有關的應用通常都包括一些共同的操做, 最多見的一個, 就是找附近的東東(餐館, 商店, 妞....). 因此, 這裏就拋出了一個問題, 怎樣才能在大量經緯度數據中檢索出附近的點呢?php
geohash能作到:android
例如: 假設個人數據庫裏存儲着1億條包含經緯度的用戶數據,用iPhone/android手機定位獲得 新浪總部(理想國際大廈)的經緯度: 39.98123848, 116.30683690 而後去數據庫查找附近的妞 github
require_once('geohash.class.php'); $geohash = new Geohash; //獲得這點的hash值 $hash = $geohash->encode(39.98123848, 116.30683690); //取前綴,前綴約長範圍越小 $prefix = substr($hash, 0, 6); //取出相鄰八個區域 $neighbors = $geohash->neighbors($prefix); array_push($neighbors, $prefix); print_r($neighbors);
//獲得9個geohash值 Array ( [top] => wx4eqx [bottom] => wx4eqt [right] => wx4eqy [left] => wx4eqq [topleft] => wx4eqr [topright] => wx4eqz [bottomright] => wx4eqv [bottomleft] => wx4eqm [0] => wx4eqw )
SELECT * FROM xy WHERE geohash LIKE 'wx4eqw%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqx%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqt%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqy%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqq%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqr%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqz%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqv%'; SELECT * FROM xy WHERE geohash LIKE 'wx4eqm%';
索引:sql
數據:數據庫
EXPLAIN SELECT * FROM xy WHERE geohash LIKE 'wx4eqw%';
恩, HOHO!!微信
其餘資料:
- geohash演示: http://openlocation.org/geohash/geohash-js/
- wiki: http://en.wikipedia.org/wiki/Geohash
- 原理: https://github.com/CloudSide/geohash/wikiide