-
Notifications
You must be signed in to change notification settings - Fork 152
/
map.js
664 lines (544 loc) · 24.7 KB
/
map.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
// Map
// Instance of a map intended for drawing to a div.
//
// * `parent` (required DOM element)
// Can also be an ID of a DOM element
// * `layerOrLayers` (required MM.Layer or Array of MM.Layers)
// each one must implement draw(), destroy(), have a .parent DOM element and a .map property
// (an array of URL templates or MM.MapProviders is also acceptable)
// * `dimensions` (optional Point)
// Size of map to create
// * `eventHandlers` (optional Array)
// If empty or null MouseHandler will be used
// Otherwise, each handler will be called with init(map)
MM.Map = function(parent, layerOrLayers, dimensions, eventHandlers) {
if (typeof parent == 'string') {
parent = document.getElementById(parent);
if (!parent) {
throw 'The ID provided to modest maps could not be found.';
}
}
this.parent = parent;
// we're no longer adding width and height to parent.style but we still
// need to enforce padding, overflow and position otherwise everything screws up
// TODO: maybe console.warn if the current values are bad?
this.parent.style.padding = '0';
this.parent.style.overflow = 'hidden';
var position = MM.getStyle(this.parent, 'position');
if (position != 'relative' && position != 'absolute') {
this.parent.style.position = 'relative';
}
this.layers = [];
if(!(layerOrLayers instanceof Array)) {
layerOrLayers = [ layerOrLayers ];
}
for (var i = 0; i < layerOrLayers.length; i++) {
this.addLayer(layerOrLayers[i]);
}
// default to Google-y Mercator style maps
this.projection = new MM.MercatorProjection(0,
MM.deriveTransformation(-Math.PI, Math.PI, 0, 0,
Math.PI, Math.PI, 1, 0,
-Math.PI, -Math.PI, 0, 1));
this.tileSize = new MM.Point(256, 256);
// default 0-18 zoom level
// with infinite horizontal pan and clamped vertical pan
this.coordLimits = [
new MM.Coordinate(0,-Infinity,0), // top left outer
new MM.Coordinate(1,Infinity,0).zoomTo(18) // bottom right inner
];
// eyes towards null island
this.coordinate = new MM.Coordinate(0.5, 0.5, 0);
// if you don't specify dimensions we assume you want to fill the parent
// unless the parent has no w/h, in which case we'll still use a default
if (!dimensions) {
dimensions = new MM.Point(this.parent.offsetWidth,
this.parent.offsetHeight);
this.autoSize = true;
// use destroy to get rid of this handler from the DOM
MM.addEvent(window, 'resize', this.windowResize());
} else {
this.autoSize = false;
// don't call setSize here because it calls draw()
this.parent.style.width = Math.round(dimensions.x) + 'px';
this.parent.style.height = Math.round(dimensions.y) + 'px';
}
this.dimensions = dimensions;
this.callbackManager = new MM.CallbackManager(this, [
'zoomed',
'panned',
'centered',
'extentset',
'resized',
'drawn'
]);
// set up handlers last so that all required attributes/functions are in place if needed
if (eventHandlers === undefined) {
this.eventHandlers = [
new MM.MouseHandler(this),
new MM.TouchHandler(this)
];
} else {
this.eventHandlers = eventHandlers;
if (eventHandlers instanceof Array) {
for (var j = 0; j < eventHandlers.length; j++) {
eventHandlers[j].init(this);
}
}
}
};
MM.Map.prototype = {
parent: null, // DOM Element
dimensions: null, // MM.Point with x/y size of parent element
projection: null, // MM.Projection of first known layer
coordinate: null, // Center of map MM.Coordinate with row/column/zoom
tileSize: null, // MM.Point with x/y size of tiles
coordLimits: null, // Array of [ topLeftOuter, bottomLeftInner ] MM.Coordinates
layers: null, // Array of MM.Layer (interface = .draw(), .destroy(), .parent and .map)
callbackManager: null, // MM.CallbackManager, handles map events
eventHandlers: null, // Array of interaction handlers, just a MM.MouseHandler by default
autoSize: null, // Boolean, true if we have a window resize listener
toString: function() {
return 'Map(#' + this.parent.id + ')';
},
// callbacks...
addCallback: function(event, callback) {
this.callbackManager.addCallback(event, callback);
return this;
},
removeCallback: function(event, callback) {
this.callbackManager.removeCallback(event, callback);
return this;
},
dispatchCallback: function(event, message) {
this.callbackManager.dispatchCallback(event, message);
return this;
},
windowResize: function() {
if (!this._windowResize) {
var theMap = this;
this._windowResize = function(event) {
// don't call setSize here because it sets parent.style.width/height
// and setting the height breaks percentages and default styles
theMap.dimensions = new MM.Point(theMap.parent.offsetWidth, theMap.parent.offsetHeight);
theMap.draw();
theMap.dispatchCallback('resized', [theMap.dimensions]);
};
}
return this._windowResize;
},
// A convenience function to restrict interactive zoom ranges.
// (you should also adjust map provider to restrict which tiles get loaded,
// or modify map.coordLimits and provider.tileLimits for finer control)
setZoomRange: function(minZoom, maxZoom) {
this.coordLimits[0] = this.coordLimits[0].zoomTo(minZoom);
this.coordLimits[1] = this.coordLimits[1].zoomTo(maxZoom);
},
// zooming
zoomBy: function(zoomOffset) {
this.coordinate = this.enforceLimits(this.coordinate.zoomBy(zoomOffset));
MM.getFrame(this.getRedraw());
this.dispatchCallback('zoomed', zoomOffset);
return this;
},
zoomIn: function() { return this.zoomBy(1); },
zoomOut: function() { return this.zoomBy(-1); },
setZoom: function(z) { return this.zoomBy(z - this.coordinate.zoom); },
zoomByAbout: function(zoomOffset, point) {
var location = this.pointLocation(point);
this.coordinate = this.enforceLimits(this.coordinate.zoomBy(zoomOffset));
var newPoint = this.locationPoint(location);
this.dispatchCallback('zoomed', zoomOffset);
return this.panBy(point.x - newPoint.x, point.y - newPoint.y);
},
// panning
panBy: function(dx, dy) {
this.coordinate.column -= dx / this.tileSize.x;
this.coordinate.row -= dy / this.tileSize.y;
this.coordinate = this.enforceLimits(this.coordinate);
// Defer until the browser is ready to draw.
MM.getFrame(this.getRedraw());
this.dispatchCallback('panned', [dx, dy]);
return this;
},
/*
panZoom: function(dx, dy, zoom) {
this.coordinate.column -= dx / this.tileSize.x;
this.coordinate.row -= dy / this.tileSize.y;
this.coordinate = this.coordinate.zoomTo(zoom);
// Defer until the browser is ready to draw.
MM.getFrame(this.getRedraw());
this.dispatchCallback('panned', [dx, dy]);
return this;
},
*/
panLeft: function() { return this.panBy(100, 0); },
panRight: function() { return this.panBy(-100, 0); },
panDown: function() { return this.panBy(0, -100); },
panUp: function() { return this.panBy(0, 100); },
// positioning
setCenter: function(location) {
return this.setCenterZoom(location, this.coordinate.zoom);
},
setCenterZoom: function(location, zoom) {
this.coordinate = this.projection.locationCoordinate(location).zoomTo(parseFloat(zoom) || 0);
MM.getFrame(this.getRedraw());
this.dispatchCallback('centered', [location, zoom]);
return this;
},
setExtent: function(locations, precise) {
// coerce locations to an array if it's a MapExtent instance
if (locations instanceof MM.MapExtent) {
locations = locations.toArray();
}
var TL, BR;
for (var i = 0; i < locations.length; i++) {
var coordinate = this.projection.locationCoordinate(locations[i]);
if (TL) {
TL.row = Math.min(TL.row, coordinate.row);
TL.column = Math.min(TL.column, coordinate.column);
TL.zoom = Math.min(TL.zoom, coordinate.zoom);
BR.row = Math.max(BR.row, coordinate.row);
BR.column = Math.max(BR.column, coordinate.column);
BR.zoom = Math.max(BR.zoom, coordinate.zoom);
}
else {
TL = coordinate.copy();
BR = coordinate.copy();
}
}
var width = this.dimensions.x + 1;
var height = this.dimensions.y + 1;
// multiplication factor between horizontal span and map width
var hFactor = (BR.column - TL.column) / (width / this.tileSize.x);
// multiplication factor expressed as base-2 logarithm, for zoom difference
var hZoomDiff = Math.log(hFactor) / Math.log(2);
// possible horizontal zoom to fit geographical extent in map width
var hPossibleZoom = TL.zoom - (precise ? hZoomDiff : Math.ceil(hZoomDiff));
// multiplication factor between vertical span and map height
var vFactor = (BR.row - TL.row) / (height / this.tileSize.y);
// multiplication factor expressed as base-2 logarithm, for zoom difference
var vZoomDiff = Math.log(vFactor) / Math.log(2);
// possible vertical zoom to fit geographical extent in map height
var vPossibleZoom = TL.zoom - (precise ? vZoomDiff : Math.ceil(vZoomDiff));
// initial zoom to fit extent vertically and horizontally
var initZoom = Math.min(hPossibleZoom, vPossibleZoom);
// additionally, make sure it's not outside the boundaries set by map limits
initZoom = Math.min(initZoom, this.coordLimits[1].zoom);
initZoom = Math.max(initZoom, this.coordLimits[0].zoom);
// coordinate of extent center
var centerRow = (TL.row + BR.row) / 2;
var centerColumn = (TL.column + BR.column) / 2;
var centerZoom = TL.zoom;
this.coordinate = new MM.Coordinate(centerRow, centerColumn, centerZoom).zoomTo(initZoom);
this.draw(); // draw calls enforceLimits
// (if you switch to getFrame, call enforceLimits first)
this.dispatchCallback('extentset', locations);
return this;
},
// Resize the map's container `<div>`, redrawing the map and triggering
// `resized` to make sure that the map's presentation is still correct.
setSize: function(dimensions) {
// Ensure that, whether a raw object or a Point object is passed,
// this.dimensions will be a Point.
this.dimensions = new MM.Point(dimensions.x, dimensions.y);
this.parent.style.width = Math.round(this.dimensions.x) + 'px';
this.parent.style.height = Math.round(this.dimensions.y) + 'px';
if (this.autoSize) {
MM.removeEvent(window, 'resize', this.windowResize());
this.autoSize = false;
}
this.draw(); // draw calls enforceLimits
// (if you switch to getFrame, call enforceLimits first)
this.dispatchCallback('resized', this.dimensions);
return this;
},
// projecting points on and off screen
coordinatePoint: function(coord) {
// Return an x, y point on the map image for a given coordinate.
if (coord.zoom != this.coordinate.zoom) {
coord = coord.zoomTo(this.coordinate.zoom);
}
// distance from the center of the map
var point = new MM.Point(this.dimensions.x / 2, this.dimensions.y / 2);
point.x += this.tileSize.x * (coord.column - this.coordinate.column);
point.y += this.tileSize.y * (coord.row - this.coordinate.row);
return point;
},
// Get a `MM.Coordinate` from an `MM.Point` - returns a new tile-like object
// from a screen point.
pointCoordinate: function(point) {
// new point coordinate reflecting distance from map center, in tile widths
var coord = this.coordinate.copy();
coord.column += (point.x - this.dimensions.x / 2) / this.tileSize.x;
coord.row += (point.y - this.dimensions.y / 2) / this.tileSize.y;
return coord;
},
// Return an MM.Coordinate (row,col,zoom) for an MM.Location (lat,lon).
locationCoordinate: function(location) {
return this.projection.locationCoordinate(location);
},
// Return an MM.Location (lat,lon) for an MM.Coordinate (row,col,zoom).
coordinateLocation: function(coordinate) {
return this.projection.coordinateLocation(coordinate);
},
// Return an x, y point on the map image for a given geographical location.
locationPoint: function(location) {
return this.coordinatePoint(this.locationCoordinate(location));
},
// Return a geographical location on the map image for a given x, y point.
pointLocation: function(point) {
return this.coordinateLocation(this.pointCoordinate(point));
},
// inspecting
getExtent: function() {
var extent = [];
extent.push(this.pointLocation(new MM.Point(0, 0)));
extent.push(this.pointLocation(this.dimensions));
return extent;
},
extent: function(locations, precise) {
if (locations) {
return this.setExtent(locations, precise);
} else {
return this.getExtent();
}
},
// Get the current centerpoint of the map, returning a `Location`
getCenter: function() {
return this.projection.coordinateLocation(this.coordinate);
},
center: function(location) {
if (location) {
return this.setCenter(location);
} else {
return this.getCenter();
}
},
// Get the current zoom level of the map, returning a number
getZoom: function() {
return this.coordinate.zoom;
},
zoom: function(zoom) {
if (zoom !== undefined) {
return this.setZoom(zoom);
} else {
return this.getZoom();
}
},
// return a copy of the layers array
getLayers: function() {
return this.layers.slice();
},
// return the layer at the given index
getLayerAt: function(index) {
return this.layers[index];
},
// put the given layer on top of all the others
addLayer: function(layer) {
this.layers.push(layer);
this.parent.appendChild(layer.parent);
layer.map = this; // TODO: remove map property from MM.Layer?
return this;
},
// find the given layer and remove it
removeLayer: function(layer) {
for (var i = 0; i < this.layers.length; i++) {
if (layer == this.layers[i]) {
this.removeLayerAt(i);
break;
}
}
return this;
},
// replace the current layer at the given index with the given layer
setLayerAt: function(index, layer) {
if (index < 0 || index >= this.layers.length) {
throw new Error('invalid index in setLayerAt(): ' + index);
}
if (this.layers[index] != layer) {
// clear existing layer at this index
if (index < this.layers.length) {
this.layers[index].destroy();
}
// pass it on.
this.layers[index] = layer;
this.parent.appendChild(layer.parent);
layer.map = this; // TODO: remove map property from MM.Layer
MM.getFrame(this.getRedraw());
}
return this;
},
// put the given layer at the given index, moving others if necessary
insertLayerAt: function(index, layer) {
if (index < 0 || index > this.layers.length) {
throw new Error('invalid index in insertLayerAt(): ' + index);
}
if (index == this.layers.length) {
// it just gets tacked on to the end
this.layers.push(layer);
this.parent.appendChild(layer.parent);
} else {
// it needs to get slipped in amongst the others
var other = this.layers[index];
this.parent.insertBefore(layer.parent, other.parent);
this.layers.splice(index, 0, layer);
}
layer.map = this; // TODO: remove map property from MM.Layer
MM.getFrame(this.getRedraw());
return this;
},
// remove the layer at the given index, call .destroy() on the layer
removeLayerAt: function(index) {
if (index < 0 || index >= this.layers.length) {
throw new Error('invalid index in removeLayer(): ' + index);
}
// gone baby gone.
var old = this.layers[index];
this.layers.splice(index, 1);
old.destroy();
return this;
},
// switch the stacking order of two layers, by index
swapLayersAt: function(i, j) {
if (i < 0 || i >= this.layers.length || j < 0 || j >= this.layers.length) {
throw new Error('invalid index in swapLayersAt(): ' + index);
}
var layer1 = this.layers[i],
layer2 = this.layers[j],
dummy = document.createElement('div');
// kick layer2 out, replace it with the dummy.
this.parent.replaceChild(dummy, layer2.parent);
// put layer2 back in and kick layer1 out
this.parent.replaceChild(layer2.parent, layer1.parent);
// put layer1 back in and ditch the dummy
this.parent.replaceChild(layer1.parent, dummy);
// now do it to the layers array
this.layers[i] = layer2;
this.layers[j] = layer1;
return this;
},
// limits
enforceZoomLimits: function(coord) {
var limits = this.coordLimits;
if (limits) {
// clamp zoom level:
var minZoom = limits[0].zoom;
var maxZoom = limits[1].zoom;
if (coord.zoom < minZoom) {
coord = coord.zoomTo(minZoom);
}
else if (coord.zoom > maxZoom) {
coord = coord.zoomTo(maxZoom);
}
}
return coord;
},
enforcePanLimits: function(coord) {
var limits = this.coordLimits;
if (limits) {
coord = coord.copy();
// clamp pan:
var topLeftLimit = limits[0].zoomTo(coord.zoom);
var bottomRightLimit = limits[1].zoomTo(coord.zoom);
var currentTopLeft = this.pointCoordinate(new MM.Point(0,0));
var currentBottomRight = this.pointCoordinate(this.dimensions);
// this handles infinite limits:
// (Infinity - Infinity) is Nan
// NaN is never less than anything
if (bottomRightLimit.row - topLeftLimit.row < currentBottomRight.row - currentTopLeft.row) {
// if the limit is smaller than the current view center it
coord.row = (bottomRightLimit.row + topLeftLimit.row) / 2;
}
else {
if (currentTopLeft.row < topLeftLimit.row) {
coord.row += topLeftLimit.row - currentTopLeft.row;
}
else if (currentBottomRight.row > bottomRightLimit.row) {
coord.row -= currentBottomRight.row - bottomRightLimit.row;
}
}
if (bottomRightLimit.column - topLeftLimit.column < currentBottomRight.column - currentTopLeft.column) {
// if the limit is smaller than the current view, center it
coord.column = (bottomRightLimit.column + topLeftLimit.column) / 2;
}
else {
if (currentTopLeft.column < topLeftLimit.column) {
coord.column += topLeftLimit.column - currentTopLeft.column;
}
else if (currentBottomRight.column > bottomRightLimit.column) {
coord.column -= currentBottomRight.column - bottomRightLimit.column;
}
}
}
return coord;
},
// Prevent accidentally navigating outside the `coordLimits` of the map.
enforceLimits: function(coord) {
return this.enforcePanLimits(this.enforceZoomLimits(coord));
},
// rendering
// Redraw the tiles on the map, reusing existing tiles.
draw: function() {
// make sure we're not too far in or out:
this.coordinate = this.enforceLimits(this.coordinate);
// if we don't have dimensions, check the parent size
if (this.dimensions.x <= 0 || this.dimensions.y <= 0) {
if (this.autoSize) {
// maybe the parent size has changed?
var w = this.parent.offsetWidth,
h = this.parent.offsetHeight;
this.dimensions = new MM.Point(w,h);
if (w <= 0 || h <= 0) {
return;
}
} else {
// the issue can only be corrected with setSize
return;
}
}
// draw layers one by one
for(var i = 0; i < this.layers.length; i++) {
this.layers[i].draw();
}
this.dispatchCallback('drawn');
},
_redrawTimer: undefined,
requestRedraw: function() {
// we'll always draw within 1 second of this request,
// sometimes faster if there's already a pending redraw
// this is used when a new tile arrives so that we clear
// any parent/child tiles that were only being displayed
// until the tile loads at the right zoom level
if (!this._redrawTimer) {
this._redrawTimer = setTimeout(this.getRedraw(), 1000);
}
},
_redraw: null,
getRedraw: function() {
// let's only create this closure once...
if (!this._redraw) {
var theMap = this;
this._redraw = function() {
theMap.draw();
theMap._redrawTimer = 0;
};
}
return this._redraw;
},
// Attempts to destroy all attachment a map has to a page
// and clear its memory usage.
destroy: function() {
for (var j = 0; j < this.layers.length; j++) {
this.layers[j].destroy();
}
this.layers = [];
this.projection = null;
for (var i = 0; i < this.eventHandlers.length; i++) {
this.eventHandlers[i].remove();
}
if (this.autoSize) {
MM.removeEvent(window, 'resize', this.windowResize());
}
}
};