(一)经纬度转GeoHash
(二)GeoHash转经纬度
import java.util.ArrayList;
import java.util.List;
public class GeoHashHelper {
public final double Max_Lat = 90;
public final double Min_Lat = -90;
public final double Max_Lng = 180;
public final double Min_Lng = -180;
private static int latLength;
private static int lngLength;
private final double latUnit = (Max_Lat - Min_Lat) / (1 << latLength);
private final double lngUnit = (Max_Lng - Min_Lng) / (1 << lngLength);
private final String[] 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"
};
private void convert(double min, double max, double value, int count, List<Character> list) {
if (list.size() > (count - 1)) {
return;
}
double mid = (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);
}
}
private String base32Encode(final String str) {
System.out.println(str);
String unit = "";
StringBuilder sb = new StringBuilder();
for (int start = 0; start < str.length(); start = start + 5) {
unit = str.substring(start, start + 5);
sb.append(base32Lookup[convertToIndex(unit)]);
}
return sb.toString();
}
private int convertToIndex(String str) {
int length = str.length();
int result = 0;
for (int index = 0; index < length; index++) {
result += str.charAt(index) == '0' ? 0 : 1 << (length - 1 - index);
}
System.out.println(result);
return result;
}
public String encode(double lat, double lng) {
if (latLength < 1 || lngLength < 1) {
return "";
}
List<Character> latList = new ArrayList<>(latLength);
List<Character> lngList = new ArrayList<>(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);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < latList.size(); index++) {
sb.append(lngList.get(index)).append(latList.get(index));
}
if (lngLength != latLength) {
sb.append(lngList.get(lngList.size() - 1));
}
return base32Encode(sb.toString());
}
public String getGeoHash(double lat, double lng, int precise) {
if (precise < 1 || precise > 9) {
return "";
}
latLength = (precise * 5) / 2;
if (precise % 2 == 0) {
lngLength = latLength;
} else {
lngLength = latLength + 1;
}
return encode(lat, lng);
}
public String getGeoHash6(double lat, double lng) {
latLength = 15;
lngLength = 15;
return encode(lat, lng);
}
public String getGeoHash7(double lat, double lng) {
latLength = 17;
lngLength = 18;
return encode(lat, lng);
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(new GeoHashHelper().getGeoHash(39.928167, 116.389550, 7));
System.out.println("waste time: " + (System.currentTimeMillis() - start) + "ms");
}
}