forked from stamen/modestmaps-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modestmaps.js
2970 lines (2546 loc) · 107 KB
/
modestmaps.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
/*!
* Modest Maps JS v1.0.0-alpha
* http://modestmaps.com/
*
* Copyright (c) 2011 Stamen Design, All Rights Reserved.
*
* Open source under the BSD License.
* http://creativecommons.org/licenses/BSD/
*
* Versioned using Semantic Versioning (v.major.minor.patch)
* See CHANGELOG and http://semver.org/ for more details.
*
*/
var previousMM = MM;
// namespacing for backwards-compatibility
if (!com) {
var com = {};
if (!com.modestmaps) com.modestmaps = {};
}
var MM = com.modestmaps = {
noConflict: function() {
MM = previousMM;
return this;
}
};
(function(MM) {
// Make inheritance bearable: clone one level of properties
MM.extend = function(child, parent) {
for (var property in parent.prototype) {
if (typeof child.prototype[property] == "undefined") {
child.prototype[property] = parent.prototype[property];
}
}
return child;
};
MM.getFrame = function () {
// native animation frames
// http://webstuff.nfshost.com/anim-timing/Overview.html
// http://dev.chromium.org/developers/design-documents/requestanimationframe-implementation
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// can't apply these directly to MM because Chrome needs window
// to own webkitRequestAnimationFrame (for example)
// perhaps we should namespace an alias onto window instead?
// e.g. window.mmRequestAnimationFrame?
return function(callback) {
(window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(function () {
callback(+new Date());
}, 10);
})(callback);
};
}();
// Inspired by LeafletJS
MM.transformProperty = (function(props) {
if (!this.document) return; // node.js safety
var style = document.documentElement.style;
for (var i = 0; i < props.length; i++) {
if (props[i] in style) {
return props[i];
}
}
return false;
})(['transformProperty', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
MM.matrixString = function(point) {
// Make the result of point.scale * point.width a whole number.
if (point.scale * point.width % 1) {
point.scale += (1 - point.scale * point.width % 1) / point.width;
}
return 'matrix3d(' +
1 + ',' + 0 + ',' + 0 + ',' + 0 + ',' +
0 + ',' + 1 + ',' + 0 + ',' + 0 + ',' +
0 + ',' + 0 + ',' + 1 + ',' + 0 + ',' +
point.x.toFixed(4) + ',' +
point.y.toFixed(4) + ',' +
0 + ',' + ((1 / point.scale) || 1) + ')';
};
MM._browser = (function(window) {
return {
webkit: ('WebKitCSSMatrix' in window),
webkit3d: ('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix())
};
})(this); // use this for node.js global
MM.moveElement = function(el, point) {
if (MM.transformProperty && MM._browser.webkit3d) {
// Optimize for identity transforms, where you don't actually
// need to change this element's string. Browsers can optimize for
// the .style.left case but not for this CSS case.
if (!point.scale) point.scale = 1;
if (!point.width) point.width = 0;
if (!point.height) point.height = 0;
var ms = MM.matrixString(point);
if (el[MM.transformProperty] !== ms) {
el.style[MM.transformProperty] =
el[MM.transformProperty] = ms;
}
} else {
el.style.left = point.x + 'px';
el.style.top = point.y + 'px';
// Don't set width unless asked to: this is performance-intensive
// and not always necessary
if (point.width && point.height && point.scale) {
el.style.width = Math.ceil(point.width * point.scale) + 'px';
el.style.height = Math.ceil(point.height * point.scale) + 'px';
}
}
};
// Events
// Cancel an event: prevent it from bubbling
MM.cancelEvent = function(e) {
// there's more than one way to skin this cat
e.cancelBubble = true;
e.cancel = true;
e.returnValue = false;
if (e.stopPropagation) { e.stopPropagation(); }
if (e.preventDefault) { e.preventDefault(); }
return false;
};
// From underscore.js
MM.bind = function(func, obj) {
var slice = Array.prototype.slice;
var nativeBind = Function.prototype.bind;
if (func.bind === nativeBind && nativeBind) {
return nativeBind.apply(func, slice.call(arguments, 1));
}
var args = slice.call(arguments, 2);
return function() {
return func.apply(obj, args.concat(slice.call(arguments)));
};
};
MM.coerceLayer = function(layerish) {
if (typeof layerish == 'string') {
// Probably a template string
return new MM.Layer(new MM.TemplatedMapProvider(layerish));
} else if ('draw' in layerish && typeof layerish.draw == 'function') {
// good enough, though we should probably enforce .parent and .destroy() too
return layerish;
} else {
// probably a MapProvider
return new MM.Layer(layerish);
}
};
// see http://ejohn.org/apps/jselect/event.html for the originals
MM.addEvent = function(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
if (type == 'mousewheel') {
obj.addEventListener('DOMMouseScroll', fn, false);
}
} else if (obj.attachEvent) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){ obj['e'+type+fn](window.event); };
obj.attachEvent('on'+type, obj[type+fn]);
}
};
MM.removeEvent = function( obj, type, fn ) {
if (obj.removeEventListener) {
obj.removeEventListener(type, fn, false);
if (type == 'mousewheel') {
obj.removeEventListener('DOMMouseScroll', fn, false);
}
} else if (obj.detachEvent) {
obj.detachEvent('on'+type, obj[type+fn]);
obj[type+fn] = null;
}
};
// Cross-browser function to get current element style property
MM.getStyle = function(el,styleProp) {
if (el.currentStyle)
return el.currentStyle[styleProp];
else if (window.getComputedStyle)
return document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
};
// Point
MM.Point = function(x, y) {
this.x = parseFloat(x);
this.y = parseFloat(y);
};
MM.Point.prototype = {
x: 0,
y: 0,
toString: function() {
return "(" + this.x.toFixed(3) + ", " + this.y.toFixed(3) + ")";
},
copy: function() {
return new MM.Point(this.x, this.y);
}
};
// Get the euclidean distance between two points
MM.Point.distance = function(p1, p2) {
return Math.sqrt(
Math.pow(p2.x - p1.x, 2) +
Math.pow(p2.y - p1.y, 2));
};
// Get a point between two other points, biased by `t`.
MM.Point.interpolate = function(p1, p2, t) {
return new MM.Point(
p1.x + (p2.x - p1.x) * t,
p1.y + (p2.y - p1.y) * t);
};
// Coordinate
// ----------
// An object representing a tile position, at as specified zoom level.
// This is not necessarily a precise tile - `row`, `column`, and
// `zoom` can be floating-point numbers, and the `container()` function
// can be used to find the actual tile that contains the point.
MM.Coordinate = function(row, column, zoom) {
this.row = row;
this.column = column;
this.zoom = zoom;
};
MM.Coordinate.prototype = {
row: 0,
column: 0,
zoom: 0,
toString: function() {
return "(" + this.row.toFixed(3) +
", " + this.column.toFixed(3) +
" @" + this.zoom.toFixed(3) + ")";
},
// Quickly generate a string representation of this coordinate to
// index it in hashes.
toKey: function() {
// We've tried to use efficient hash functions here before but we took
// them out. Contributions welcome but watch out for collisions when the
// row or column are negative and check thoroughly (exhaustively) before
// committing.
return this.zoom + ',' + this.row + ',' + this.column;
},
// Clone this object.
copy: function() {
return new MM.Coordinate(this.row, this.column, this.zoom);
},
// Get the actual, rounded-number tile that contains this point.
container: function() {
// using floor here (not parseInt, ~~) because we want -0.56 --> -1
return new MM.Coordinate(Math.floor(this.row),
Math.floor(this.column),
Math.floor(this.zoom));
},
// Recalculate this Coordinate at a different zoom level and return the
// new object.
zoomTo: function(destination) {
var power = Math.pow(2, destination - this.zoom);
return new MM.Coordinate(this.row * power,
this.column * power,
destination);
},
// Recalculate this Coordinate at a different relative zoom level and return the
// new object.
zoomBy: function(distance) {
var power = Math.pow(2, distance);
return new MM.Coordinate(this.row * power,
this.column * power,
this.zoom + distance);
},
// Move this coordinate up by `dist` coordinates
up: function(dist) {
if (dist === undefined) dist = 1;
return new MM.Coordinate(this.row - dist, this.column, this.zoom);
},
// Move this coordinate right by `dist` coordinates
right: function(dist) {
if (dist === undefined) dist = 1;
return new MM.Coordinate(this.row, this.column + dist, this.zoom);
},
// Move this coordinate down by `dist` coordinates
down: function(dist) {
if (dist === undefined) dist = 1;
return new MM.Coordinate(this.row + dist, this.column, this.zoom);
},
// Move this coordinate left by `dist` coordinates
left: function(dist) {
if (dist === undefined) dist = 1;
return new MM.Coordinate(this.row, this.column - dist, this.zoom);
}
};
// Location
// --------
MM.Location = function(lat, lon) {
this.lat = parseFloat(lat);
this.lon = parseFloat(lon);
};
MM.Location.prototype = {
lat: 0,
lon: 0,
toString: function() {
return "(" + this.lat.toFixed(3) + ", " + this.lon.toFixed(3) + ")";
},
copy: function() {
return new MM.Location(this.lat, this.lon);
}
};
// returns approximate distance between start and end locations
//
// default unit is meters
//
// you can specify different units by optionally providing the
// earth's radius in the units you desire
//
// Default is 6,378,000 metres, suggested values are:
//
// * 3963.1 statute miles
// * 3443.9 nautical miles
// * 6378 km
//
// see [Formula and code for calculating distance based on two lat/lon locations](http://jan.ucc.nau.edu/~cvm/latlon_formula.html)
MM.Location.distance = function(l1, l2, r) {
if (!r) {
// default to meters
r = 6378000;
}
var deg2rad = Math.PI / 180.0,
a1 = l1.lat * deg2rad,
b1 = l1.lon * deg2rad,
a2 = l2.lat * deg2rad,
b2 = l2.lon * deg2rad,
c = Math.cos(a1) * Math.cos(b1) * Math.cos(a2) * Math.cos(b2),
d = Math.cos(a1) * Math.sin(b1) * Math.cos(a2) * Math.sin(b2),
e = Math.sin(a1) * Math.sin(a2);
return Math.acos(c + d + e) * r;
};
// Interpolates along a great circle, f between 0 and 1
//
// * FIXME: could be heavily optimized (lots of trig calls to cache)
// * FIXME: could be inmproved for calculating a full path
MM.Location.interpolate = function(l1, l2, f) {
if (l1.lat === l2.lat && l1.lon === l2.lon) {
return new MM.Location(l1.lat, l1.lon);
}
var deg2rad = Math.PI / 180.0,
lat1 = l1.lat * deg2rad,
lon1 = l1.lon * deg2rad,
lat2 = l2.lat * deg2rad,
lon2 = l2.lon * deg2rad;
var d = 2 * Math.asin(
Math.sqrt(
Math.pow(Math.sin((lat1 - lat2) / 2), 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
var bearing = Math.atan2(
Math.sin(lon1 - lon2) *
Math.cos(lat2),
Math.cos(lat1) *
Math.sin(lat2) -
Math.sin(lat1) *
Math.cos(lat2) *
Math.cos(lon1 - lon2)
) / -(Math.PI / 180);
bearing = bearing < 0 ? 360 + bearing : bearing;
var A = Math.sin((1-f)*d)/Math.sin(d);
var B = Math.sin(f*d)/Math.sin(d);
var x = A * Math.cos(lat1) * Math.cos(lon1) +
B * Math.cos(lat2) * Math.cos(lon2);
var y = A * Math.cos(lat1) * Math.sin(lon1) +
B * Math.cos(lat2) * Math.sin(lon2);
var z = A * Math.sin(lat1) + B * Math.sin(lat2);
var latN = Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
var lonN = Math.atan2(y,x);
return new MM.Location(latN / deg2rad, lonN / deg2rad);
};
// Extent
// ----------
// An object representing a map's rectangular extent, defined by its north,
// south, east and west bounds.
MM.Extent = function(north, west, south, east) {
if (arguments[0] instanceof MM.Location) {
var northwest = arguments[0];
north = northwest.lat;
west = northwest.lon;
}
if (arguments[1] instanceof MM.Location) {
var southeast = arguments[1];
south = southeast.lat;
east = southeast.lon;
}
if (isNaN(south)) south = north;
if (isNaN(east)) east = west;
this.north = Math.max(north, south);
this.south = Math.min(north, south);
this.east = Math.max(east, west);
this.west = Math.min(east, west);
};
MM.Extent.prototype = {
// boundary attributes
north: 0,
south: 0,
east: 0,
west: 0,
copy: function() {
return new MM.Extent(this.north, this.west, this.south, this.east);
},
toString: function(precision) {
if (isNaN(precision)) precision = 3;
return [
this.north.toFixed(precision),
this.west.toFixed(precision),
this.south.toFixed(precision),
this.east.toFixed(precision)
].join(", ");
},
// getters for the corner locations
northWest: function() {
return new MM.Location(this.north, this.west);
},
southEast: function() {
return new MM.Location(this.south, this.east);
},
northEast: function() {
return new MM.Location(this.north, this.east);
},
southWest: function() {
return new MM.Location(this.south, this.west);
},
// getter for the center location
center: function() {
return new MM.Location(
this.south + (this.north - this.south) / 2,
this.east + (this.west - this.east) / 2
);
},
// extend the bounds to include a location's latitude and longitude
encloseLocation: function(loc) {
if (loc.lat > this.north) this.north = loc.lat;
if (loc.lat < this.south) this.south = loc.lat;
if (loc.lon > this.east) this.east = loc.lon;
if (loc.lon < this.west) this.west = loc.lon;
},
// extend the bounds to include multiple locations
encloseLocations: function(locations) {
var len = locations.length;
for (var i = 0; i < len; i++) {
this.encloseLocation(locations[i]);
}
},
// reset bounds from a list of locations
setFromLocations: function(locations) {
var len = locations.length,
first = locations[0];
this.north = this.south = first.lat;
this.east = this.west = first.lon;
for (var i = 1; i < len; i++) {
this.encloseLocation(locations[i]);
}
},
// extend the bounds to include another extent
encloseExtent: function(extent) {
if (extent.north > this.north) this.north = extent.north;
if (extent.south < this.south) this.south = extent.south;
if (extent.east > this.east) this.east = extent.east;
if (extent.west < this.west) this.west = extent.west;
},
// determine if a location is within this extent
containsLocation: function(loc) {
return loc.lat >= this.south &&
loc.lat <= this.north &&
loc.lon >= this.west &&
loc.lon <= this.east;
},
// turn an extent into an array of locations containing its northwest
// and southeast corners (used in MM.Map.setExtent())
toArray: function() {
return [this.northWest(), this.southEast()];
}
};
MM.Extent.fromString = function(str) {
var parts = str.split(/\s*,\s*/);
if (parts.length != 4) {
throw "Invalid extent string (expecting 4 comma-separated numbers)";
}
return new MM.Extent(
parseFloat(parts[0]),
parseFloat(parts[1]),
parseFloat(parts[2]),
parseFloat(parts[3])
);
};
MM.Extent.fromArray = function(locations) {
var extent = new MM.Extent();
extent.setFromLocations(locations);
return extent;
};
// Transformation
// --------------
MM.Transformation = function(ax, bx, cx, ay, by, cy) {
this.ax = ax;
this.bx = bx;
this.cx = cx;
this.ay = ay;
this.by = by;
this.cy = cy;
};
MM.Transformation.prototype = {
ax: 0,
bx: 0,
cx: 0,
ay: 0,
by: 0,
cy: 0,
transform: function(point) {
return new MM.Point(this.ax * point.x + this.bx * point.y + this.cx,
this.ay * point.x + this.by * point.y + this.cy);
},
untransform: function(point) {
return new MM.Point((point.x * this.by - point.y * this.bx -
this.cx * this.by + this.cy * this.bx) /
(this.ax * this.by - this.ay * this.bx),
(point.x * this.ay - point.y * this.ax -
this.cx * this.ay + this.cy * this.ax) /
(this.bx * this.ay - this.by * this.ax));
}
};
// Generates a transform based on three pairs of points,
// a1 -> a2, b1 -> b2, c1 -> c2.
MM.deriveTransformation = function(a1x, a1y, a2x, a2y,
b1x, b1y, b2x, b2y,
c1x, c1y, c2x, c2y) {
var x = MM.linearSolution(a1x, a1y, a2x,
b1x, b1y, b2x,
c1x, c1y, c2x);
var y = MM.linearSolution(a1x, a1y, a2y,
b1x, b1y, b2y,
c1x, c1y, c2y);
return new MM.Transformation(x[0], x[1], x[2], y[0], y[1], y[2]);
};
// Solves a system of linear equations.
//
// t1 = (a * r1) + (b + s1) + c
// t2 = (a * r2) + (b + s2) + c
// t3 = (a * r3) + (b + s3) + c
//
// r1 - t3 are the known values.
// a, b, c are the unknowns to be solved.
// returns the a, b, c coefficients.
MM.linearSolution = function(r1, s1, t1, r2, s2, t2, r3, s3, t3) {
// make them all floats
r1 = parseFloat(r1);
s1 = parseFloat(s1);
t1 = parseFloat(t1);
r2 = parseFloat(r2);
s2 = parseFloat(s2);
t2 = parseFloat(t2);
r3 = parseFloat(r3);
s3 = parseFloat(s3);
t3 = parseFloat(t3);
var a = (((t2 - t3) * (s1 - s2)) - ((t1 - t2) * (s2 - s3))) /
(((r2 - r3) * (s1 - s2)) - ((r1 - r2) * (s2 - s3)));
var b = (((t2 - t3) * (r1 - r2)) - ((t1 - t2) * (r2 - r3))) /
(((s2 - s3) * (r1 - r2)) - ((s1 - s2) * (r2 - r3)));
var c = t1 - (r1 * a) - (s1 * b);
return [ a, b, c ];
};
// Projection
// ----------
// An abstract class / interface for projections
MM.Projection = function(zoom, transformation) {
if (!transformation) {
transformation = new MM.Transformation(1, 0, 0, 0, 1, 0);
}
this.zoom = zoom;
this.transformation = transformation;
};
MM.Projection.prototype = {
zoom: 0,
transformation: null,
rawProject: function(point) {
throw "Abstract method not implemented by subclass.";
},
rawUnproject: function(point) {
throw "Abstract method not implemented by subclass.";
},
project: function(point) {
point = this.rawProject(point);
if(this.transformation) {
point = this.transformation.transform(point);
}
return point;
},
unproject: function(point) {
if(this.transformation) {
point = this.transformation.untransform(point);
}
point = this.rawUnproject(point);
return point;
},
locationCoordinate: function(location) {
var point = new MM.Point(Math.PI * location.lon / 180.0,
Math.PI * location.lat / 180.0);
point = this.project(point);
return new MM.Coordinate(point.y, point.x, this.zoom);
},
coordinateLocation: function(coordinate) {
coordinate = coordinate.zoomTo(this.zoom);
var point = new MM.Point(coordinate.column, coordinate.row);
point = this.unproject(point);
return new MM.Location(180.0 * point.y / Math.PI,
180.0 * point.x / Math.PI);
}
};
// A projection for equilateral maps, based on longitude and latitude
MM.LinearProjection = function(zoom, transformation) {
MM.Projection.call(this, zoom, transformation);
};
// The Linear projection doesn't reproject points
MM.LinearProjection.prototype = {
rawProject: function(point) {
return new MM.Point(point.x, point.y);
},
rawUnproject: function(point) {
return new MM.Point(point.x, point.y);
}
};
MM.extend(MM.LinearProjection, MM.Projection);
MM.MercatorProjection = function(zoom, transformation) {
// super!
MM.Projection.call(this, zoom, transformation);
};
// Project lon/lat points into meters required for Mercator
MM.MercatorProjection.prototype = {
rawProject: function(point) {
return new MM.Point(point.x,
Math.log(Math.tan(0.25 * Math.PI + 0.5 * point.y)));
},
rawUnproject: function(point) {
return new MM.Point(point.x,
2 * Math.atan(Math.pow(Math.E, point.y)) - 0.5 * Math.PI);
}
};
MM.extend(MM.MercatorProjection, MM.Projection);
// Providers
// ---------
// Providers provide tile URLs and possibly elements for layers.
//
// MapProvider ->
// TemplatedMapProvider
//
MM.MapProvider = function(getTile) {
if (getTile) {
this.getTile = getTile;
}
};
MM.MapProvider.prototype = {
// these are limits for available *tiles*
// panning limits will be different (since you can wrap around columns)
// but if you put Infinity in here it will screw up sourceCoordinate
tileLimits: [
new MM.Coordinate(0,0,0), // top left outer
new MM.Coordinate(1,1,0).zoomTo(18) // bottom right inner
],
getTileUrl: function(coordinate) {
throw "Abstract method not implemented by subclass.";
},
getTile: function(coordinate) {
throw "Abstract method not implemented by subclass.";
},
// releaseTile is not required
releaseTile: function(element) { },
// use this to tell MapProvider that tiles only exist between certain zoom levels.
// should be set separately on Map to restrict interactive zoom/pan ranges
setZoomRange: function(minZoom, maxZoom) {
this.tileLimits[0] = this.tileLimits[0].zoomTo(minZoom);
this.tileLimits[1] = this.tileLimits[1].zoomTo(maxZoom);
},
// return null if coord is above/below row extents
// wrap column around the world if it's outside column extents
// ... you should override this function if you change the tile limits
// ... see enforce-limits in examples for details
sourceCoordinate: function(coord) {
var TL = this.tileLimits[0].zoomTo(coord.zoom),
BR = this.tileLimits[1].zoomTo(coord.zoom),
columnSize = Math.pow(2, coord.zoom),
wrappedColumn;
if (coord.column < 0) {
wrappedColumn = (coord.column + columnSize) % columnSize;
} else {
wrappedColumn = coord.column % columnSize;
}
if (coord.row < TL.row || coord.row >= BR.row) {
return null;
} else if (wrappedColumn < TL.column || wrappedColumn >= BR.column) {
return null;
} else {
return new MM.Coordinate(coord.row, wrappedColumn, coord.zoom);
}
}
};
/**
* FIXME: need a better explanation here! This is a pretty crucial part of
* understanding how to use ModestMaps.
*
* TemplatedMapProvider is a tile provider that generates tile URLs from a
* template string by replacing the following bits for each tile
* coordinate:
*
* {Z}: the tile's zoom level (from 1 to ~20)
* {X}: the tile's X, or column (from 0 to a very large number at higher
* zooms)
* {Y}: the tile's Y, or row (from 0 to a very large number at higher
* zooms)
*
* E.g.:
*
* var osm = new MM.TemplatedMapProvider("http://tile.openstreetmap.org/{Z}/{X}/{Y}.png");
*
* Or:
*
* var placeholder = new MM.TemplatedMapProvider("http://placehold.it/256/f0f/fff.png&text={Z}/{X}/{Y}");
*
*/
MM.TemplatedMapProvider = function(template, subdomains) {
var isQuadKey = template.match(/{(Q|quadkey)}/);
// replace Microsoft style substitution strings
if (isQuadKey) template = template
.replace('{subdomains}', '{S}')
.replace('{zoom}', '{Z}')
.replace('{quadkey}', '{Q}');
var hasSubdomains = (subdomains &&
subdomains.length && template.indexOf("{S}") >= 0);
var getTileUrl = function(coordinate) {
var coord = this.sourceCoordinate(coordinate);
if (!coord) {
return null;
}
var base = template;
if (hasSubdomains) {
var index = parseInt(coord.zoom + coord.row + coord.column, 10) %
subdomains.length;
base = base.replace('{S}', subdomains[index]);
}
if (isQuadKey) {
return base
.replace('{Z}', coord.zoom.toFixed(0))
.replace('{Q}', this.quadKey(coord.row,
coord.column,
coord.zoom));
} else {
return base
.replace('{Z}', coord.zoom.toFixed(0))
.replace('{X}', coord.column.toFixed(0))
.replace('{Y}', coord.row.toFixed(0));
}
};
MM.MapProvider.call(this, getTileUrl);
};
MM.TemplatedMapProvider.prototype = {
// quadKey generator
quadKey: function(row, column, zoom) {
var key = '';
for (var i = 1; i <= zoom; i++) {
key += (((row >> zoom - i) & 1) << 1) | ((column >> zoom - i) & 1);
}
return key || '0';
},
getTile: function(coord) {
return this.getTileUrl(coord);
}
};
MM.extend(MM.TemplatedMapProvider, MM.MapProvider);
MM.TemplatedLayer = function(template, subdomains) {
return new MM.Layer(new MM.TemplatedMapProvider(template, subdomains));
};
// Event Handlers
// --------------
// A utility function for finding the offset of the
// mouse from the top-left of the page
MM.getMousePoint = function(e, map) {
// start with just the mouse (x, y)
var point = new MM.Point(e.clientX, e.clientY);
// correct for scrolled document
point.x += document.body.scrollLeft + document.documentElement.scrollLeft;
point.y += document.body.scrollTop + document.documentElement.scrollTop;
// correct for nested offsets in DOM
for (var node = map.parent; node; node = node.offsetParent) {
point.x -= node.offsetLeft;
point.y -= node.offsetTop;
}
return point;
};
// A handler that allows mouse-wheel zooming - zooming in
// when page would scroll up, and out when the page would scroll down.
MM.MouseWheelHandler = function(map, precise) {
// only init() if we get a map
if (map) {
this.init(map, precise);
// allow (null, true) as constructor args
} else if (arguments.length > 1) {
this.precise = precise ? true : false;
}
};
MM.MouseWheelHandler.prototype = {
precise: false,
init: function(map) {
this.map = map;
this._mouseWheel = MM.bind(this.mouseWheel, this);
this._zoomDiv = document.body.appendChild(document.createElement('div'));
this._zoomDiv.style.cssText = 'visibility:hidden;top:0;height:0;width:0;overflow-y:scroll';
var innerDiv = this._zoomDiv.appendChild(document.createElement('div'));
innerDiv.style.height = '2000px';
MM.addEvent(map.parent, 'mousewheel', this._mouseWheel);
},
remove: function() {
MM.removeEvent(this.map.parent, 'mousewheel', this._mouseWheel);
this._zoomDiv.parentNode.removeChild(this._zoomDiv);
},
mouseWheel: function(e) {
var delta = 0;
this.prevTime = this.prevTime || new Date().getTime();
try {
this._zoomDiv.scrollTop = 1000;
this._zoomDiv.dispatchEvent(e);
delta = 1000 - this._zoomDiv.scrollTop;
} catch (error) {
delta = e.wheelDelta || (-e.detail * 5);
}
// limit mousewheeling to once every 200ms
var timeSince = new Date().getTime() - this.prevTime;
if (Math.abs(delta) > 0 && (timeSince > 200) && !this.precise) {
var point = MM.getMousePoint(e, this.map);
this.map.zoomByAbout(delta > 0 ? 1 : -1, point);
this.prevTime = new Date().getTime();
} else if (this.precise) {
var point = MM.getMousePoint(e, this.map);
this.map.zoomByAbout(delta * 0.001, point);
}
// Cancel the event so that the page doesn't scroll
return MM.cancelEvent(e);
}
};
// Handle double clicks, that zoom the map in one zoom level.
MM.DoubleClickHandler = function(map) {
if (map !== undefined) {
this.init(map);
}
};
MM.DoubleClickHandler.prototype = {
init: function(map) {
this.map = map;
this._doubleClick = MM.bind(this.doubleClick, this);
MM.addEvent(map.parent, 'dblclick', this._doubleClick);
},
remove: function() {
MM.removeEvent(this.map.parent, 'dblclick', this._doubleClick);
},
doubleClick: function(e) {
// Ensure that this handler is attached once.
// Get the point on the map that was double-clicked
var point = MM.getMousePoint(e, this.map);
// use shift-double-click to zoom out
this.map.zoomByAbout(e.shiftKey ? -1 : 1, point);
return MM.cancelEvent(e);
}
};
// Handle the use of mouse dragging to pan the map.
MM.DragHandler = function(map) {
if (map !== undefined) {
this.init(map);
}
};
MM.DragHandler.prototype = {
init: function(map) {
this.map = map;
this._mouseDown = MM.bind(this.mouseDown, this);
MM.addEvent(map.parent, 'mousedown', this._mouseDown);
},
remove: function() {
MM.removeEvent(this.map.parent, 'mousedown', this._mouseDown);
},
mouseDown: function(e) {
MM.addEvent(document, 'mouseup', this._mouseUp = MM.bind(this.mouseUp, this));
MM.addEvent(document, 'mousemove', this._mouseMove = MM.bind(this.mouseMove, this));
this.prevMouse = new MM.Point(e.clientX, e.clientY);
this.map.parent.style.cursor = 'move';
return MM.cancelEvent(e);
},
mouseMove: function(e) {
if (this.prevMouse) {
this.map.fastForward = true;
this.map.panBy(
e.clientX - this.prevMouse.x,