-
Notifications
You must be signed in to change notification settings - Fork 0
/
encodedpolyline.js
105 lines (88 loc) · 2.57 KB
/
encodedpolyline.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
function EncodedPolyline () { }
(function () {
var _encode = function (v) {
var negative = v < 0;
if (negative) {
v = (~(-v)) + 1;
v = v * 2; // <<1
v = ~(v);
} else {
v = v * 2; // <<1
}
var r = [];
while (v) {
var x = v & 0b11111;
v = v >>> 5;
if (v) x = x | 0x20;
r.push (String.fromCharCode (x + 63));
}
if (!r.length) return String.fromCharCode (0 + 63);
return r.join ('');
}; // _encode
EncodedPolyline.encode = function (points, f) {
if (!points.length) return '';
var n = points[0].length;
if (!n) return '';
var r = "";
var current = [];
for (var i = 0; i < n; i++) current[i] = 0;
for (var i = 0; i < points.length; i++) {
var pt = points[i];
for (var j = 0; j < n; j++) {
var v = Math.floor (((pt[j] - current[j]) * f) + 0.5);
r += _encode (v);
current[j] += v / f;
}
}
return r;
}; // encode
EncodedPolyline.decode = function (input, n, f) {
var current = [];
for (var i = 0; i < n; i++) current[i] = 0;
var r = [];
var i = 0;
var matched = true;
while (matched) {
matched = false;
input = input.replace (/^([\x5F-\x7E]*[\x3F-\x5E])/, function (x) {
var v = 0;
x.split (/(?:)/).reverse ().forEach (function (y) {
v = v * (2 ** 5);
v = v | ((y.charCodeAt (0) - 63) & 0b11111);
});
if (v & 1) {
v = v >>> 1;
v = -~(~(v)-1);
} else {
v = v >>> 1;
}
var j = i % n;
v = current[j] = current[j] + v;
if (j) {
r[r.length-1][j] = v / f;
} else {
r.push ([v / f]);
}
i++;
matched = true;
return '';
});
} // matched
return r;
}; // decode
}) ();
/* License
Copyright 2016-2018 Wakaba <wakaba@suikawiki.org>.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/