public static String encodePolygon(List coordinates, int[] encodeOffsets){
StringBuilder result = new StringBuilder("");
int prevX = encodeOffsets[0];
int prevY = encodeOffsets[1];
for (int i = 0; i < coordinates.size(); i++) {
List point = (List) coordinates.get(i);
String x = point.get(0).toString();
String y = point.get(1).toString();
result.append(encode(Double.valueOf(x), prevX));
result.append(encode(Double.valueOf(y), prevY));
prevX = quantize(Double.valueOf(x));
prevY = quantize(Double.valueOf(y));
}
return result.toString();
}
private static String encode(double d, int prev) {
// Quantization
int val = quantize(d);
// Delta
val = val - prev;
if (((val << 1) ^ (val >> 15)) + 64 == 8232) {
//WTF, 8232 will get syntax error in js code
val--;
}
// ZigZag
val = (val << 1) ^ (val >> 15);
// add offset and get unicode
return String.valueOf((char)(val + 64));
}
public static int quantize(double d) {
return (int)Math.ceil(d * 1024);
}
private static List decodePolygon(String coordinate, int prevX, int prevY) {
List result = new ArrayList();
for (int i = 0; i < coordinate.length(); i += 2) {
int x = coordinate.toCharArray()[i] - 64;
int y = coordinate.toCharArray()[i + 1] - 64;
// ZigZag decoding
x = (x >> 1) ^ -(x & 1);
y = (y >> 1) ^ -(y & 1);
// Delta deocding
x += prevX;
y += prevY;
prevX = x;
prevY = y;
// Dequantize
double[] c = new double[]{(double) x / 1024,(double) y / 1024};
result.add(c);
}
return result;
}