summaryrefslogtreecommitdiff
path: root/misc/openlayers/lib/OpenLayers/Format/EncodedPolyline.js
blob: e10e8b27e31a447944262ce8d605e3a4f0c638c7 (plain)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the 2-clause BSD license.
 * See license.txt in the OpenLayers distribution or repository for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format.js
 * @requires OpenLayers/Feature/Vector.js
 */

/**
 * Class: OpenLayers.Format.EncodedPolyline
 * Class for reading and writing encoded polylines.  Create a new instance
 * with the <OpenLayers.Format.EncodedPolyline> constructor.
 *
 * Inherits from:
 *  - <OpenLayers.Format>
 */
OpenLayers.Format.EncodedPolyline = OpenLayers.Class(OpenLayers.Format, {

    /**
     * APIProperty: geometryType
     * {String} Geometry type to output. One of: linestring (default),
     *     linearring, point, multipoint or polygon. If the geometryType is
     *     point, only the first point of the string is returned.
     */
    geometryType: "linestring",

    /**
     * Constructor: OpenLayers.Format.EncodedPolyline
     * Create a new parser for encoded polylines
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *           this instance
     *
     * Returns:
     * {<OpenLayers.Format.EncodedPolyline>} A new encoded polylines parser.
     */
    initialize: function(options) {
        OpenLayers.Format.prototype.initialize.apply(this, [options]);
    },

    /**
     * APIMethod: read
     * Deserialize an encoded polyline string and return a vector feature.
     *
     * Parameters:
     * encoded - {String} An encoded polyline string
     *
     * Returns:
     * {<OpenLayers.Feature.Vector>} A vector feature with a linestring.
     */
    read: function(encoded) {
        var geomType;
        if (this.geometryType == "linestring")
            geomType = OpenLayers.Geometry.LineString;
        else if (this.geometryType == "linearring")
            geomType = OpenLayers.Geometry.LinearRing;
        else if (this.geometryType == "multipoint")
            geomType = OpenLayers.Geometry.MultiPoint;
        else if (this.geometryType != "point" && this.geometryType != "polygon")
            return null;

        var flatPoints = this.decodeDeltas(encoded, 2);
        var flatPointsLength = flatPoints.length;

        var pointGeometries = [];
        for (var i = 0; i + 1 < flatPointsLength;) {
            var y = flatPoints[i++], x = flatPoints[i++];
            pointGeometries.push(new OpenLayers.Geometry.Point(x, y));
        }


        if (this.geometryType == "point")
            return new OpenLayers.Feature.Vector(
                pointGeometries[0]
            );

        if (this.geometryType == "polygon")
            return new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Polygon([
                    new OpenLayers.Geometry.LinearRing(pointGeometries)
                ])
            );

        return new OpenLayers.Feature.Vector(
            new geomType(pointGeometries)
        );
    },

    /**
     * APIMethod: decode
     * Deserialize an encoded string and return an array of n-dimensional
     * points.
     *
     * Parameters:
     * encoded - {String} An encoded string
     * dims - {int} The dimension of the points that are returned
     *
     * Returns:
     * {Array(Array(int))} An array containing n-dimensional arrays of
     *     coordinates.
     */
    decode: function(encoded, dims, opt_factor) {
        var factor = opt_factor || 1e5;
        var flatPoints = this.decodeDeltas(encoded, dims, factor);
        var flatPointsLength = flatPoints.length;

        var points = [];
        for (var i = 0; i + (dims - 1) < flatPointsLength;) {
            var point = [];

            for (var dim = 0; dim < dims; ++dim) {
                point.push(flatPoints[i++])
            }

            points.push(point);
        }

        return points;
    },

    /**
     * APIMethod: write
     * Serialize a feature or array of features into a WKT string.
     *
     * Parameters:
     * features - {<OpenLayers.Feature.Vector>|Array} A feature or array of
     *            features
     *
     * Returns:
     * {String} The WKT string representation of the input geometries
     */
    write: function(features) {
        var feature;
        if (features.constructor == Array)
            feature = features[0];
        else
            feature = features;

        var geometry = feature.geometry;
        var type = geometry.CLASS_NAME.split('.')[2].toLowerCase();

        var pointGeometries;
        if (type == "point")
            pointGeometries = new Array(geometry);
        else if (type == "linestring" ||
                 type == "linearring" ||
                 type == "multipoint")
            pointGeometries = geometry.components;
        else if (type == "polygon")
            pointGeometries = geometry.components[0].components;
        else
            return null;

        var flatPoints = [];

        var pointGeometriesLength = pointGeometries.length;
        for (var i = 0; i < pointGeometriesLength; ++i) {
            var pointGeometry = pointGeometries[i];
            flatPoints.push(pointGeometry.y);
            flatPoints.push(pointGeometry.x);
        }

        return this.encodeDeltas(flatPoints, 2);
    },

    /**
     * APIMethod: encode
     * Serialize an array of n-dimensional points and return an encoded string
     *
     * Parameters:
     * points - {Array(Array(int))} An array containing n-dimensional
     *          arrays of coordinates
     * dims - {int} The dimension of the points that should be read
     *
     * Returns:
     * {String} An encoded string
     */
    encode: function (points, dims, opt_factor) {
        var factor = opt_factor || 1e5;
        var flatPoints = [];

        var pointsLength = points.length;
        for (var i = 0; i < pointsLength; ++i) {
            var point = points[i];

            for (var dim = 0; dim < dims; ++dim) {
                flatPoints.push(point[dim]);
            }
        }

        return this.encodeDeltas(flatPoints, dims, factor);
    },

    /**
     * APIMethod: encodeDeltas
     * Encode a list of n-dimensional points and return an encoded string
     *
     * Attention: This function will modify the passed array!
     *
     * Parameters:
     * numbers - {Array.<number>} A list of n-dimensional points.
     * dimension - {number} The dimension of the points in the list.
     * opt_factor - {number=} The factor by which the numbers will be
     * multiplied. The remaining decimal places will get rounded away.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeDeltas: function(numbers, dimension, opt_factor) {
      var factor = opt_factor || 1e5;
      var d;

      var lastNumbers = new Array(dimension);
      for (d = 0; d < dimension; ++d) {
        lastNumbers[d] = 0;
      }

      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength;) {
        for (d = 0; d < dimension; ++d, ++i) {
          var num = numbers[i];
          var delta = num - lastNumbers[d];
          lastNumbers[d] = num;

          numbers[i] = delta;
        }
      }

      return this.encodeFloats(numbers, factor);
    },


    /**
     * APIMethod: decodeDeltas
     * Decode a list of n-dimensional points from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     * dimension - {number} The dimension of the points in the encoded string.
     * opt_factor - {number=} The factor by which the resulting numbers will
     * be divided.
     *
     * Returns:
     * {Array.<number>} A list of n-dimensional points.
     */
    decodeDeltas: function(encoded, dimension, opt_factor) {
      var factor = opt_factor || 1e5;
      var d;

      var lastNumbers = new Array(dimension);
      for (d = 0; d < dimension; ++d) {
        lastNumbers[d] = 0;
      }

      var numbers = this.decodeFloats(encoded, factor);

      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength;) {
        for (d = 0; d < dimension; ++d, ++i) {
          lastNumbers[d] += numbers[i];

          numbers[i] = lastNumbers[d];
        }
      }

      return numbers;
    },


    /**
     * APIMethod: encodeFloats
     * Encode a list of floating point numbers and return an encoded string
     *
     * Attention: This function will modify the passed array!
     *
     * Parameters:
     * numbers - {Array.<number>} A list of floating point numbers.
     * opt_factor - {number=} The factor by which the numbers will be
     * multiplied. The remaining decimal places will get rounded away.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeFloats: function(numbers, opt_factor) {
      var factor = opt_factor || 1e5;

      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength; ++i) {
        numbers[i] = Math.round(numbers[i] * factor);
      }

      return this.encodeSignedIntegers(numbers);
    },


    /**
     * APIMethod: decodeFloats
     * Decode a list of floating point numbers from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     * opt_factor - {number=} The factor by which the result will be divided.
     *
     * Returns:
     * {Array.<number>} A list of floating point numbers.
     */
    decodeFloats: function(encoded, opt_factor) {
      var factor = opt_factor || 1e5;

      var numbers = this.decodeSignedIntegers(encoded);

      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength; ++i) {
        numbers[i] /= factor;
      }

      return numbers;
    },


    /**
     * APIMethod: encodeSignedIntegers
     * Encode a list of signed integers and return an encoded string
     *
     * Attention: This function will modify the passed array!
     *
     * Parameters:
     * numbers - {Array.<number>} A list of signed integers.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeSignedIntegers: function(numbers) {
      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength; ++i) {
        var num = numbers[i];

        var signedNum = num << 1;
        if (num < 0) {
          signedNum = ~(signedNum);
        }

        numbers[i] = signedNum;
      }

      return this.encodeUnsignedIntegers(numbers);
    },


    /**
     * APIMethod: decodeSignedIntegers
     * Decode a list of signed integers from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     *
     * Returns:
     * {Array.<number>} A list of signed integers.
     */
    decodeSignedIntegers: function(encoded) {
      var numbers = this.decodeUnsignedIntegers(encoded);

      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength; ++i) {
        var num = numbers[i];
        numbers[i] = (num & 1) ? ~(num >> 1) : (num >> 1);
      }

      return numbers;
    },


    /**
     * APIMethod: encodeUnsignedIntegers
     * Encode a list of unsigned integers and return an encoded string
     *
     * Parameters:
     * numbers - {Array.<number>} A list of unsigned integers.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeUnsignedIntegers: function(numbers) {
      var encoded = '';

      var numbersLength = numbers.length;
      for (var i = 0; i < numbersLength; ++i) {
        encoded += this.encodeUnsignedInteger(numbers[i]);
      }

      return encoded;
    },


    /**
     * APIMethod: decodeUnsignedIntegers
     * Decode a list of unsigned integers from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     *
     * Returns:
     * {Array.<number>} A list of unsigned integers.
     */
    decodeUnsignedIntegers: function(encoded) {
      var numbers = [];

      var current = 0;
      var shift = 0;

      var encodedLength = encoded.length;
      for (var i = 0; i < encodedLength; ++i) {
        var b = encoded.charCodeAt(i) - 63;

        current |= (b & 0x1f) << shift;

        if (b < 0x20) {
          numbers.push(current);
          current = 0;
          shift = 0;
        } else {
          shift += 5;
        }
      }

      return numbers;
    },


    /**
     * Method: encodeFloat
     * Encode one single floating point number and return an encoded string
     *
     * Parameters:
     * num - {number} Floating point number that should be encoded.
     * opt_factor - {number=} The factor by which num will be multiplied.
     * The remaining decimal places will get rounded away.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeFloat: function(num, opt_factor) {
      num = Math.round(num * (opt_factor || 1e5));
      return this.encodeSignedInteger(num);
    },


    /**
     * Method: decodeFloat
     * Decode one single floating point number from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     * opt_factor - {number=} The factor by which the result will be divided.
     *
     * Returns:
     * {number} The decoded floating point number.
     */
    decodeFloat: function(encoded, opt_factor) {
      var result = this.decodeSignedInteger(encoded);
      return result / (opt_factor || 1e5);
    },


    /**
     * Method: encodeSignedInteger
     * Encode one single signed integer and return an encoded string
     *
     * Parameters:
     * num - {number} Signed integer that should be encoded.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeSignedInteger: function(num) {
      var signedNum = num << 1;
      if (num < 0) {
        signedNum = ~(signedNum);
      }

      return this.encodeUnsignedInteger(signedNum);
    },


    /**
     * Method: decodeSignedInteger
     * Decode one single signed integer from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     *
     * Returns:
     * {number} The decoded signed integer.
     */
    decodeSignedInteger: function(encoded) {
      var result = this.decodeUnsignedInteger(encoded);
      return ((result & 1) ? ~(result >> 1) : (result >> 1));
    },


    /**
     * Method: encodeUnsignedInteger
     * Encode one single unsigned integer and return an encoded string
     *
     * Parameters:
     * num - {number} Unsigned integer that should be encoded.
     *
     * Returns:
     * {string} The encoded string.
     */
    encodeUnsignedInteger: function(num) {
      var value, encoded = '';
      while (num >= 0x20) {
        value = (0x20 | (num & 0x1f)) + 63;
        encoded += (String.fromCharCode(value));
        num >>= 5;
      }
      value = num + 63;
      encoded += (String.fromCharCode(value));
      return encoded;
    },


    /**
     * Method: decodeUnsignedInteger
     * Decode one single unsigned integer from an encoded string
     *
     * Parameters:
     * encoded - {string} An encoded string.
     *
     * Returns:
     * {number} The decoded unsigned integer.
     */
    decodeUnsignedInteger: function(encoded) {
      var result = 0;
      var shift = 0;

      var encodedLength = encoded.length;
      for (var i = 0; i < encodedLength; ++i) {
        var b = encoded.charCodeAt(i) - 63;

        result |= (b & 0x1f) << shift;

        if (b < 0x20)
          break;

        shift += 5;
      }

      return result;
    },

    CLASS_NAME: "OpenLayers.Format.EncodedPolyline"
});