尋找附近網點geohash演算法及實現 (Java版本),geohashjava
參考文檔:
http://blog.csdn.net/wangxiafghj/article/details/9014363geohash 演算法原理及實現方式
http://blog.charlee.li/geohash-intro/ geohash:用字串實現附近地點搜尋
http://blog.sina.com.cn/s/blog_7c05385f0101eofb.html 尋找附近點--Geohash方案討論
http://www.wubiao.info/372 尋找附近的xxx 球面距離以及Geohash方案探討
http://en.wikipedia.org/wiki/Haversine_formula Haversine formula球面距離公式
http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe 球面距離公式代碼實現
http://developer.baidu.com/map/jsdemo.htm#a6_1 球面距離公式驗證
http://www.wubiao.info/470 Mysql or Mongodb LBS快速實現方案
geohash有以下幾個特點:
首先,geohash用一個字串表示經度和緯度兩個座標。某些情況下無法在兩列上同時應用索引 (例如MySQL 4之前的版本,Google App Engine的資料層等),利用geohash,只需在一列上應用索引即可。
其次,geohash表示的並不是一個點,而是一個矩形地區。比如編碼wx4g0ec19,它表示的是一個矩形地區。 使用者發行就緒地址編碼,既能表明自己位於北海公園附近,又不至於暴露自己的精確座標,有助於隱私保護。
第三,編碼的首碼可以表示更大的地區。例如wx4g0ec1,它的首碼wx4g0e表示包含編碼wx4g0ec1在內的更大範圍。 這個特性可以用於附近地點搜尋。首先根據使用者當前座標計算geohash(例如wx4g0ec1)然後取其首碼進行查詢 (SELECT * FROM place WHERE geohash LIKE 'wx4g0e%'),即可查詢附近的所有地點。
Geohash比直接用經緯度的高效很多。
Geohash演算法實現(Java版本)
package com.DistTest;import java.util.BitSet;import java.util.HashMap;public class Geohash { private static int numbits = 6 * 5; final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; final static HashMap<Character, Integer> lookup = new HashMap<Character, Integer>(); static { int i = 0; for (char c : digits) lookup.put(c, i++); } public double[] decode(String geohash) { StringBuilder buffer = new StringBuilder(); for (char c : geohash.toCharArray()) { int i = lookup.get(c) + 32; buffer.append( Integer.toString(i, 2).substring(1) ); } BitSet lonset = new BitSet(); BitSet latset = new BitSet(); //even bits int j =0; for (int i=0; i< numbits*2;i+=2) { boolean isSet = false; if ( i < buffer.length() ) isSet = buffer.charAt(i) == '1'; lonset.set(j++, isSet); } //odd bits j=0; for (int i=1; i< numbits*2;i+=2) { boolean isSet = false; if ( i < buffer.length() ) isSet = buffer.charAt(i) == '1'; latset.set(j++, isSet); } //中國地理座標:東經73°至東經135°,北緯4°至北緯53° double lon = decode(lonset, 70, 140); double lat = decode(latset, 0, 60); return new double[] {lat, lon}; } private double decode(BitSet bs, double floor, double ceiling) { double mid = 0; for (int i=0; i<bs.length(); i++) { mid = (floor + ceiling) / 2; if (bs.get(i)) floor = mid; else ceiling = mid; } return mid; } public String encode(double lat, double lon) { BitSet latbits = getBits(lat, 0, 60); BitSet lonbits = getBits(lon, 70, 140); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < numbits; i++) { buffer.append( (lonbits.get(i))?'1':'0'); buffer.append( (latbits.get(i))?'1':'0'); } return base32(Long.parseLong(buffer.toString(), 2)); } private BitSet getBits(double lat, double floor, double ceiling) { BitSet buffer = new BitSet(numbits); for (int i = 0; i < numbits; i++) { double mid = (floor + ceiling) / 2; if (lat >= mid) { buffer.set(i); floor = mid; } else { ceiling = mid; } } return buffer; } public static String base32(long i) { char[] buf = new char[65]; int charPos = 64; boolean negative = (i < 0); if (!negative) i = -i; while (i <= -32) { buf[charPos--] = digits[(int) (-(i % 32))]; i /= 32; } buf[charPos] = digits[(int) (-i)]; if (negative) buf[--charPos] = '-'; return new String(buf, charPos, (65 - charPos)); }}
球面距離公式:
package com.DistTest;public class Test{ private static final double EARTH_RADIUS = 6371000;//赤道半徑(單位m)/** * 轉化為弧度(rad) * */private static double rad(double d){ return d * Math.PI / 180.0;}/** * 基於googleMap中的演算法得到兩經緯度之間的距離,計算精度與Google地圖的距離精度差不多,相差範圍在0.2米以下 * @param lon1 第一點的精度 * @param lat1 第一點的緯度 * @param lon2 第二點的精度 * @param lat3 第二點的緯度 * @return 返回的距離,單位m * */public static double GetDistance(double lon1,double lat1,double lon2, double lat2){ double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lon1) - rad(lon2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2)+Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10000; return s;} public static void main(String []args){ double lon1=109.0145193757; double lat1=34.236080797698; double lon2=108.9644583556; double lat2=34.286439088548; double dist; String geocode; dist=Test.GetDistance(lon1, lat1, lon2, lat2); System.out.println("兩點相距:" + dist + " 米"); Geohash geohash = new Geohash(); geocode=geohash.encode(lat1, lon1); System.out.println("當前位置編碼:" + geocode); geocode=geohash.encode(lat2, lon2); System.out.println("遠方位置編碼:" + geocode); }//wqj7j37sfu03h2xb2q97/*永相逢超市108.8345750017734.256981052624wqj6us6cmkj5bbfj6qdgs6q08ubhhuq7*/}
附近網點距離排序
package com.DistTest; import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Connection;import java.sql.Statement; public class sqlTest { public static void main(String[] args) throws Exception { Connection conn = null; String sql; String url = "jdbc:mysql://132.97.**.**/test?" + "user=***&password=****&useUnicode=true&characterEncoding=UTF8"; try { Class.forName("com.mysql.jdbc.Driver");// 動態載入mysql驅動 // System.out.println("成功載入MySQL驅動程式"); // 一個Connection代表一個資料庫連接 conn = DriverManager.getConnection(url); // Statement裡面帶有很多方法,比如executeUpdate可以實現插入,更新和刪除等 Statement stmt = conn.createStatement(); sql = "select * from retailersinfotable limit 1,10"; ResultSet rs = stmt.executeQuery(sql);// executeQuery會返回結果的集合,否則返回空值 double lon1=109.0145193757; double lat1=34.236080797698; System.out.println("當前位置:"); int i=0; String[][] array = new String[10][3]; while (rs.next()){ //從資料庫取出地理座標 double lon2=Double.parseDouble(rs.getString("Longitude")); double lat2=Double.parseDouble(rs.getString("Latitude")); //根據地理座標,產生geohash編碼 Geohash geohash = new Geohash(); String geocode=geohash.encode(lat2, lon2).substring(0, 9); //計算兩點間的距離 int dist=(int) Test.GetDistance(lon1, lat1, lon2, lat2); array[i][0]=String.valueOf(i); array[i][1]=geocode; array[i][2]=Integer.toString(dist); i++; //System.out.println(lon2+"---"+lat2+"---"+geocode+"---"+dist); } array=sqlTest.getOrder(array); //二維數組排序 sqlTest.showArray(array); //列印數組 } catch (SQLException e) { System.out.println("MySQL操作錯誤"); e.printStackTrace(); } finally { conn.close(); } } /* * 二維數組排序,比較array[][2]的值,返回二維數組 * */ public static String[][] getOrder(String[][] array){for (int j = 0; j < array.length ; j++) {for (int bb = 0; bb < array.length - 1; bb++) {String[] ss;int a1=Integer.valueOf(array[bb][2]); //轉化成int型比較大小int a2=Integer.valueOf(array[bb+1][2]);if (a1>a2) {ss = array[bb];array[bb] = array[bb + 1];array[bb + 1] = ss;}}} return array; } /*列印數組*/ public static void showArray(String[][] array){ for(int a=0;a<array.length;a++){ for(int j=0;j<array[0].length;j++) System.out.print(array[a][j]+" "); System.out.println(); } }}