forked from mapbox/leaflet-omnivore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
leaflet-omnivore.js
2382 lines (2101 loc) · 70 KB
/
leaflet-omnivore.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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.omnivore = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var xhr = require('corslite'),
csv2geojson = require('csv2geojson'),
wellknown = require('wellknown'),
polyline = require('polyline'),
topojson = require('topojson'),
toGeoJSON = require('togeojson');
module.exports.polyline = polylineLoad;
module.exports.polyline.parse = polylineParse;
module.exports.geojson = geojsonLoad;
module.exports.topojson = topojsonLoad;
module.exports.topojson.parse = topojsonParse;
module.exports.csv = csvLoad;
module.exports.csv.parse = csvParse;
module.exports.gpx = gpxLoad;
module.exports.gpx.parse = gpxParse;
module.exports.kml = kmlLoad;
module.exports.kml.parse = kmlParse;
module.exports.wkt = wktLoad;
module.exports.wkt.parse = wktParse;
function addData(l, d) {
if ('setGeoJSON' in l) {
l.setGeoJSON(d);
} else if ('addData' in l) {
l.addData(d);
}
}
/**
* Load a [GeoJSON](http://geojson.org/) document into a layer and return the layer.
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function geojsonLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, function(err, response) {
if (err) return layer.fire('error', { error: err });
addData(layer, JSON.parse(response.responseText));
layer.fire('ready');
});
return layer;
}
/**
* Load a [TopoJSON](https://github.com/mbostock/topojson) document into a layer and return the layer.
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function topojsonLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, onload);
function onload(err, response) {
if (err) return layer.fire('error', { error: err });
topojsonParse(response.responseText, options, layer);
layer.fire('ready');
}
return layer;
}
/**
* Load a CSV document into a layer and return the layer.
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function csvLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, onload);
function onload(err, response) {
var error;
if (err) return layer.fire('error', { error: err });
function avoidReady() {
error = true;
}
layer.on('error', avoidReady);
csvParse(response.responseText, options, layer);
layer.off('error', avoidReady);
if (!error) layer.fire('ready');
}
return layer;
}
/**
* Load a GPX document into a layer and return the layer.
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function gpxLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, onload);
function onload(err, response) {
var error;
if (err) return layer.fire('error', { error: err });
function avoidReady() {
error = true;
}
layer.on('error', avoidReady);
gpxParse(response.responseXML || response.responseText, options, layer);
layer.off('error', avoidReady);
if (!error) layer.fire('ready');
}
return layer;
}
/**
* Load a [KML](https://developers.google.com/kml/documentation/) document into a layer and return the layer.
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function kmlLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, onload);
function onload(err, response) {
var error;
if (err) return layer.fire('error', { error: err });
function avoidReady() {
error = true;
}
layer.on('error', avoidReady);
kmlParse(response.responseXML || response.responseText, options, layer);
layer.off('error', avoidReady);
if (!error) layer.fire('ready');
}
return layer;
}
/**
* Load a WKT (Well Known Text) string into a layer and return the layer
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function wktLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, onload);
function onload(err, response) {
if (err) return layer.fire('error', { error: err });
wktParse(response.responseText, options, layer);
layer.fire('ready');
}
return layer;
}
/**
* Load a polyline string into a layer and return the layer
*
* @param {string} url
* @param {object} options
* @param {object} customLayer
* @returns {object}
*/
function polylineLoad(url, options, customLayer) {
var layer = customLayer || L.geoJson();
xhr(url, onload);
function onload(err, response) {
if (err) return layer.fire('error', { error: err });
polylineParse(response.responseText, options, layer);
layer.fire('ready');
}
return layer;
}
function topojsonParse(data, options, layer) {
var o = typeof data === 'string' ?
JSON.parse(data) : data;
layer = layer || L.geoJson();
for (var i in o.objects) {
var ft = topojson.feature(o, o.objects[i]);
if (ft.features) addData(layer, ft.features);
else addData(layer, ft);
}
return layer;
}
function csvParse(csv, options, layer) {
layer = layer || L.geoJson();
options = options || {};
csv2geojson.csv2geojson(csv, options, onparse);
function onparse(err, geojson) {
if (err) return layer.fire('error', { error: err });
addData(layer, geojson);
}
return layer;
}
function gpxParse(gpx, options, layer) {
var xml = parseXML(gpx);
if (!xml) return layer.fire('error', {
error: 'Could not parse GPX'
});
layer = layer || L.geoJson();
var geojson = toGeoJSON.gpx(xml);
addData(layer, geojson);
return layer;
}
function kmlParse(gpx, options, layer) {
var xml = parseXML(gpx);
if (!xml) return layer.fire('error', {
error: 'Could not parse KML'
});
layer = layer || L.geoJson();
var geojson = toGeoJSON.kml(xml);
addData(layer, geojson);
return layer;
}
function polylineParse(txt, options, layer) {
layer = layer || L.geoJson();
options = options || {};
var coords = polyline.decode(txt, options.precision);
var geojson = { type: 'LineString', coordinates: [] };
for (var i = 0; i < coords.length; i++) {
// polyline returns coords in lat, lng order, so flip for geojson
geojson.coordinates[i] = [coords[i][1], coords[i][0]];
}
addData(layer, geojson);
return layer;
}
function wktParse(wkt, options, layer) {
layer = layer || L.geoJson();
var geojson = wellknown(wkt);
addData(layer, geojson);
return layer;
}
function parseXML(str) {
if (typeof str === 'string') {
return (new DOMParser()).parseFromString(str, 'text/xml');
} else {
return str;
}
}
},{"corslite":3,"csv2geojson":4,"polyline":6,"togeojson":9,"topojson":10,"wellknown":11}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
function corslite(url, callback, cors) {
var sent = false;
if (typeof window.XMLHttpRequest === 'undefined') {
return callback(Error('Browser not supported'));
}
if (typeof cors === 'undefined') {
var m = url.match(/^\s*https?:\/\/[^\/]*/);
cors = m && (m[0] !== location.protocol + '//' + location.hostname +
(location.port ? ':' + location.port : ''));
}
var x = new window.XMLHttpRequest();
function isSuccessful(status) {
return status >= 200 && status < 300 || status === 304;
}
if (cors && !('withCredentials' in x)) {
// IE8-9
x = new window.XDomainRequest();
// Ensure callback is never called synchronously, i.e., before
// x.send() returns (this has been observed in the wild).
// See https://github.com/mapbox/mapbox.js/issues/472
var original = callback;
callback = function() {
if (sent) {
original.apply(this, arguments);
} else {
var that = this, args = arguments;
setTimeout(function() {
original.apply(that, args);
}, 0);
}
}
}
function loaded() {
if (
// XDomainRequest
x.status === undefined ||
// modern browsers
isSuccessful(x.status)) callback.call(x, null, x);
else callback.call(x, x, null);
}
// Both `onreadystatechange` and `onload` can fire. `onreadystatechange`
// has [been supported for longer](http://stackoverflow.com/a/9181508/229001).
if ('onload' in x) {
x.onload = loaded;
} else {
x.onreadystatechange = function readystate() {
if (x.readyState === 4) {
loaded();
}
};
}
// Call the callback with the XMLHttpRequest object as an error and prevent
// it from ever being called again by reassigning it to `noop`
x.onerror = function error(evt) {
// XDomainRequest provides no evt parameter
callback.call(this, evt || true, null);
callback = function() { };
};
// IE9 must have onprogress be set to a unique function.
x.onprogress = function() { };
x.ontimeout = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
x.onabort = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
// GET is the only supported HTTP Verb by XDomainRequest and is the
// only one supported here.
x.open('GET', url, true);
// Send the request. Sending data is not supported.
x.send(null);
sent = true;
return x;
}
if (typeof module !== 'undefined') module.exports = corslite;
},{}],4:[function(require,module,exports){
'use strict';
var dsv = require('d3-dsv'),
sexagesimal = require('sexagesimal');
var latRegex = /(Lat)(itude)?/gi,
lonRegex = /(L)(on|ng)(gitude)?/i;
function guessHeader(row, regexp) {
var name, match, score;
for (var f in row) {
match = f.match(regexp);
if (match && (!name || match[0].length / f.length > score)) {
score = match[0].length / f.length;
name = f;
}
}
return name;
}
function guessLatHeader(row) { return guessHeader(row, latRegex); }
function guessLonHeader(row) { return guessHeader(row, lonRegex); }
function isLat(f) { return !!f.match(latRegex); }
function isLon(f) { return !!f.match(lonRegex); }
function keyCount(o) {
return (typeof o == 'object') ? Object.keys(o).length : 0;
}
function autoDelimiter(x) {
var delimiters = [',', ';', '\t', '|'];
var results = [];
delimiters.forEach(function (delimiter) {
var res = dsv.dsvFormat(delimiter).parse(x);
if (res.length >= 1) {
var count = keyCount(res[0]);
for (var i = 0; i < res.length; i++) {
if (keyCount(res[i]) !== count) return;
}
results.push({
delimiter: delimiter,
arity: Object.keys(res[0]).length,
});
}
});
if (results.length) {
return results.sort(function (a, b) {
return b.arity - a.arity;
})[0].delimiter;
} else {
return null;
}
}
/**
* Silly stopgap for dsv to d3-dsv upgrade
*
* @param {Array} x dsv output
* @returns {Array} array without columns member
*/
function deleteColumns(x) {
delete x.columns;
return x;
}
function auto(x) {
var delimiter = autoDelimiter(x);
if (!delimiter) return null;
return deleteColumns(dsv.dsvFormat(delimiter).parse(x));
}
function csv2geojson(x, options, callback) {
if (!callback) {
callback = options;
options = {};
}
options.delimiter = options.delimiter || ',';
var latfield = options.latfield || '',
lonfield = options.lonfield || '',
crs = options.crs || '';
var features = [],
featurecollection = {type: 'FeatureCollection', features: features};
if (crs !== '') {
featurecollection.crs = {type: 'name', properties: {name: crs}};
}
if (options.delimiter === 'auto' && typeof x == 'string') {
options.delimiter = autoDelimiter(x);
if (!options.delimiter) {
callback({
type: 'Error',
message: 'Could not autodetect delimiter'
});
return;
}
}
var parsed = (typeof x == 'string') ?
dsv.dsvFormat(options.delimiter).parse(x) : x;
if (!parsed.length) {
callback(null, featurecollection);
return;
}
var errors = [];
var i;
if (!latfield) latfield = guessLatHeader(parsed[0]);
if (!lonfield) lonfield = guessLonHeader(parsed[0]);
var noGeometry = (!latfield || !lonfield);
if (noGeometry) {
for (i = 0; i < parsed.length; i++) {
features.push({
type: 'Feature',
properties: parsed[i],
geometry: null
});
}
callback(errors.length ? errors : null, featurecollection);
return;
}
for (i = 0; i < parsed.length; i++) {
if (parsed[i][lonfield] !== undefined &&
parsed[i][latfield] !== undefined) {
var lonk = parsed[i][lonfield],
latk = parsed[i][latfield],
lonf, latf,
a;
a = sexagesimal(lonk, 'EW');
if (a) lonk = a;
a = sexagesimal(latk, 'NS');
if (a) latk = a;
lonf = parseFloat(lonk);
latf = parseFloat(latk);
if (isNaN(lonf) ||
isNaN(latf)) {
errors.push({
message: 'A row contained an invalid value for latitude or longitude',
row: parsed[i],
index: i
});
} else {
if (!options.includeLatLon) {
delete parsed[i][lonfield];
delete parsed[i][latfield];
}
features.push({
type: 'Feature',
properties: parsed[i],
geometry: {
type: 'Point',
coordinates: [
parseFloat(lonf),
parseFloat(latf)
]
}
});
}
}
}
callback(errors.length ? errors : null, featurecollection);
}
function toLine(gj) {
var features = gj.features;
var line = {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: []
}
};
for (var i = 0; i < features.length; i++) {
line.geometry.coordinates.push(features[i].geometry.coordinates);
}
line.properties = features.reduce(function (aggregatedProperties, newFeature) {
for (var key in newFeature.properties) {
if (!aggregatedProperties[key]) {
aggregatedProperties[key] = [];
}
aggregatedProperties[key].push(newFeature.properties[key]);
}
return aggregatedProperties;
}, {});
return {
type: 'FeatureCollection',
features: [line]
};
}
function toPolygon(gj) {
var features = gj.features;
var poly = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[]]
}
};
for (var i = 0; i < features.length; i++) {
poly.geometry.coordinates[0].push(features[i].geometry.coordinates);
}
poly.properties = features.reduce(function (aggregatedProperties, newFeature) {
for (var key in newFeature.properties) {
if (!aggregatedProperties[key]) {
aggregatedProperties[key] = [];
}
aggregatedProperties[key].push(newFeature.properties[key]);
}
return aggregatedProperties;
}, {});
return {
type: 'FeatureCollection',
features: [poly]
};
}
module.exports = {
isLon: isLon,
isLat: isLat,
guessLatHeader: guessLatHeader,
guessLonHeader: guessLonHeader,
csv: dsv.csvParse,
tsv: dsv.tsvParse,
dsv: dsv,
auto: auto,
csv2geojson: csv2geojson,
toLine: toLine,
toPolygon: toPolygon
};
},{"d3-dsv":5,"sexagesimal":8}],5:[function(require,module,exports){
// https://d3js.org/d3-dsv/ Version 1.0.1. Copyright 2016 Mike Bostock.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, function (exports) { 'use strict';
function objectConverter(columns) {
return new Function("d", "return {" + columns.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "]";
}).join(",") + "}");
}
function customConverter(columns, f) {
var object = objectConverter(columns);
return function(row, i) {
return f(object(row), i, columns);
};
}
// Compute unique columns in order of discovery.
function inferColumns(rows) {
var columnSet = Object.create(null),
columns = [];
rows.forEach(function(row) {
for (var column in row) {
if (!(column in columnSet)) {
columns.push(columnSet[column] = column);
}
}
});
return columns;
}
function dsv(delimiter) {
var reFormat = new RegExp("[\"" + delimiter + "\n]"),
delimiterCode = delimiter.charCodeAt(0);
function parse(text, f) {
var convert, columns, rows = parseRows(text, function(row, i) {
if (convert) return convert(row, i - 1);
columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
});
rows.columns = columns;
return rows;
}
function parseRows(text, f) {
var EOL = {}, // sentinel value for end-of-line
EOF = {}, // sentinel value for end-of-file
rows = [], // output rows
N = text.length,
I = 0, // current character index
n = 0, // the current line number
t, // the current token
eol; // is the current token followed by EOL?
function token() {
if (I >= N) return EOF; // special case: end of file
if (eol) return eol = false, EOL; // special case: end of line
// special case: quotes
var j = I, c;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < N) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
++i;
}
}
I = i + 2;
c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) ++I;
} else if (c === 10) {
eol = true;
}
return text.slice(j + 1, i).replace(/""/g, "\"");
}
// common case: find next delimiter or newline
while (I < N) {
var k = 1;
c = text.charCodeAt(I++);
if (c === 10) eol = true; // \n
else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n
else if (c !== delimiterCode) continue;
return text.slice(j, I - k);
}
// special case: last token before EOF
return text.slice(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && (a = f(a, n++)) == null) continue;
rows.push(a);
}
return rows;
}
function format(rows, columns) {
if (columns == null) columns = inferColumns(rows);
return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) {
return columns.map(function(column) {
return formatValue(row[column]);
}).join(delimiter);
})).join("\n");
}
function formatRows(rows) {
return rows.map(formatRow).join("\n");
}
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(text) {
return text == null ? ""
: reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\""
: text;
}
return {
parse: parse,
parseRows: parseRows,
format: format,
formatRows: formatRows
};
}
var csv = dsv(",");
var csvParse = csv.parse;
var csvParseRows = csv.parseRows;
var csvFormat = csv.format;
var csvFormatRows = csv.formatRows;
var tsv = dsv("\t");
var tsvParse = tsv.parse;
var tsvParseRows = tsv.parseRows;
var tsvFormat = tsv.format;
var tsvFormatRows = tsv.formatRows;
exports.dsvFormat = dsv;
exports.csvParse = csvParse;
exports.csvParseRows = csvParseRows;
exports.csvFormat = csvFormat;
exports.csvFormatRows = csvFormatRows;
exports.tsvParse = tsvParse;
exports.tsvParseRows = tsvParseRows;
exports.tsvFormat = tsvFormat;
exports.tsvFormatRows = tsvFormatRows;
Object.defineProperty(exports, '__esModule', { value: true });
}));
},{}],6:[function(require,module,exports){
'use strict';
/**
* Based off of [the offical Google document](https://developers.google.com/maps/documentation/utilities/polylinealgorithm)
*
* Some parts from [this implementation](http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoder.js)
* by [Mark McClure](http://facstaff.unca.edu/mcmcclur/)
*
* @module polyline
*/
var polyline = {};
function encode(coordinate, factor) {
coordinate = Math.round(coordinate * factor);
coordinate <<= 1;
if (coordinate < 0) {
coordinate = ~coordinate;
}
var output = '';
while (coordinate >= 0x20) {
output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63);
coordinate >>= 5;
}
output += String.fromCharCode(coordinate + 63);
return output;
}
/**
* Decodes to a [latitude, longitude] coordinates array.
*
* This is adapted from the implementation in Project-OSRM.
*
* @param {String} str
* @param {Number} precision
* @returns {Array}
*
* @see https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js
*/
polyline.decode = function(str, precision) {
var index = 0,
lat = 0,
lng = 0,
coordinates = [],
shift = 0,
result = 0,
byte = null,
latitude_change,
longitude_change,
factor = Math.pow(10, precision || 5);
// Coordinates have variable length when encoded, so just keep
// track of whether we've hit the end of the string. In each
// loop iteration, a single coordinate is decoded.
while (index < str.length) {
// Reset shift, result, and byte
byte = null;
shift = 0;
result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
shift = result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += latitude_change;
lng += longitude_change;
coordinates.push([lat / factor, lng / factor]);
}
return coordinates;
};
/**
* Encodes the given [latitude, longitude] coordinates array.
*
* @param {Array.<Array.<Number>>} coordinates
* @param {Number} precision
* @returns {String}
*/
polyline.encode = function(coordinates, precision) {
if (!coordinates.length) { return ''; }
var factor = Math.pow(10, precision || 5),
output = encode(coordinates[0][0], factor) + encode(coordinates[0][1], factor);
for (var i = 1; i < coordinates.length; i++) {
var a = coordinates[i], b = coordinates[i - 1];
output += encode(a[0] - b[0], factor);
output += encode(a[1] - b[1], factor);
}
return output;
};
function flipped(coords) {
var flipped = [];
for (var i = 0; i < coords.length; i++) {
flipped.push(coords[i].slice().reverse());
}
return flipped;
}
/**
* Encodes a GeoJSON LineString feature/geometry.
*
* @param {Object} geojson
* @param {Number} precision
* @returns {String}
*/
polyline.fromGeoJSON = function(geojson, precision) {
if (geojson && geojson.type === 'Feature') {
geojson = geojson.geometry;
}
if (!geojson || geojson.type !== 'LineString') {
throw new Error('Input must be a GeoJSON LineString');
}
return polyline.encode(flipped(geojson.coordinates), precision);
};
/**
* Decodes to a GeoJSON LineString geometry.
*
* @param {String} str
* @param {Number} precision
* @returns {Object}
*/
polyline.toGeoJSON = function(str, precision) {
var coords = polyline.decode(str, precision);
return {
type: 'LineString',
coordinates: flipped(coords)
};
};
if (typeof module === 'object' && module.exports) {
module.exports = polyline;
}
},{}],7:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}