importjava.util.ArrayList;
importjava.util.List;
publicclassGeoHashHelper {
publicfinaldoubleMax_Lat=90;
publicfinaldoubleMin_Lat=-90;
publicfinaldoubleMax_Lng=180;
publicfinaldoubleMin_Lng=-180;
privatestaticintlatLength;
privatestaticintlngLength;
privatefinaldoublelatUnit= (Max_Lat-Min_Lat) / (1<<latLength);
privatefinaldoublelngUnit= (Max_Lng-Min_Lng) / (1<<lngLength);
privatefinalString[] base32Lookup= {
"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" };
privatevoidconvert(doublemin, doublemax, doublevalue, intcount, Listlist) {
if (list.size() > (count-1)) {
return;
}
doublemid= (max+min) /2;
if (value<mid) {
list.add('0');
convert(min, mid, value, count, list);
} else {
list.add('1');
convert(mid, max, value, count, list);
}
}
privateStringbase32Encode(finalStringstr) {
System.out.println(str);
Stringunit="";
StringBuildersb=newStringBuilder();
for (intstart=0; start<str.length(); start=start+5) {
unit=str.substring(start, start+5);
sb.append(base32Lookup[convertToIndex(unit)]);
}
returnsb.toString();
}
privateintconvertToIndex(Stringstr) {
intlength=str.length();
intresult=0;
for (intindex=0; index<length; index++) {
result+=str.charAt(index) =='0'?0 : 1<< (length-1-index);
}
System.out.println(result);
returnresult;
}
publicStringencode(doublelat, doublelng) {
if (latLength<1||lngLength<1) {
return"";
}
ListlatList=newArrayList<>(latLength);
ListlngList=newArrayList<>(lngLength);
convert(Min_Lat, Max_Lat, lat, latLength, latList);
convert(Min_Lng, Max_Lng, lng, lngLength, lngList);
System.out.println("latList: "+latList);
System.out.println("lngList: "+lngList);
StringBuildersb=newStringBuilder();
for (intindex=0; index<latList.size(); index++) {
sb.append(lngList.get(index)).append(latList.get(index));
}
if (lngLength!=latLength) {
sb.append(lngList.get(lngList.size() -1));
}
returnbase32Encode(sb.toString());
}
publicStringgetGeoHash(doublelat, doublelng, intprecise) {
if (precise<1||precise>9) {
return"";
}
latLength= (precise*5) /2;
if (precise%2==0) {
lngLength=latLength;
} else {
lngLength=latLength+1;
}
returnencode(lat, lng);
}
publicStringgetGeoHash6(doublelat, doublelng) {
latLength=15;
lngLength=15;
returnencode(lat, lng);
}
publicStringgetGeoHash7(doublelat, doublelng) {
latLength=17;
lngLength=18;
returnencode(lat, lng);
}
publicstaticvoidmain(String[] args) {
longstart=System.currentTimeMillis();
System.out.println(newGeoHashHelper().getGeoHash(39.928167, 116.389550, 7));
System.out.println("waste time: "+ (System.currentTimeMillis() -start) +"ms");
}
}