其他分享
首页 > 其他分享> > GeoHash

GeoHash

作者:互联网

根据wiki algorithm https://en.wikipedia.org/wiki/Geohash

思路:纯算法实现;32位字符: 0~9 , a~z;  字符去掉了 a,i, l, o;

        // since pricision biggest is 12, each char using 5 digit which is total 60;
        // divided by two (lat, lng), then each lat and lng contribute 30;

public class GeoHash {
    /*
     * @param latitude: one of a location coordinate pair 
     * @param longitude: one of a location coordinate pair 
     * @param precision: an integer between 1 to 12
     * @return: a base32 string
     */
    public String encode(double latitude, double longitude, int precision) {
        String SPACE = "0123456789bcdefghjkmnpqrstuvwxyz";
        String latBin = getBin(latitude, -90, 90);
        String lngBin = getBin(longitude, -180, 180);
        
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 30; i++) {
            sb.append(lngBin.charAt(i));
            sb.append(latBin.charAt(i));
        }
        
        StringBuilder resBuilder = new StringBuilder();
        for(int i = 0; i < 60; i += 5) {
            int index = getIndex(sb.substring(i, i+5));
            resBuilder.append(SPACE.charAt(index));
        }
        return resBuilder.toString().substring(0, precision);
    }
    
    private int getIndex(String str) {
        return Integer.parseInt(str, 2);
    }
    
    private String getBin(double value, double start, double end) {
        // since pricision biggest is 12, each char using 5 digit which is total 60;
        // divided by two (lat, lng), then each lat and lng contribute 30;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 30; i++) {
            double mid = (start + end ) / 2;
            if(value > mid) {
                start = mid;
                sb.append("1");
            } else {
                end = mid;
                sb.append("0");
            }
        }
        return sb.toString();
    }
}

 

flyatcmu 发布了571 篇原创文章 · 获赞 13 · 访问量 17万+ 他的留言板 关注

标签:String,int,double,GeoHash,StringBuilder,sb,append
来源: https://blog.csdn.net/u013325815/article/details/104090952