forked from russss/maplibregl-layer-switcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlhash.js
107 lines (95 loc) · 2.33 KB
/
urlhash.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
class URLHash {
constructor(layerSwitcher) {
this.layerSwitcher = layerSwitcher;
this._onHashChange();
}
enable(map) {
this._map = map;
map.on('moveend', () => {
this._updateHash();
});
window.addEventListener(
'hashchange',
() => {
this._onHashChange();
},
false,
);
}
_onHashChange() {
const loc = window.location.hash.replace('#', '').split('/');
if (loc.length >= 3) {
let layerString = "";
if (this._map) {
this._map.jumpTo({
center: [+loc[2], +loc[1]],
zoom: +loc[0],
});
}
for (let i = 3; i < loc.length; i++) {
let component = loc[i];
let matches = component.match(/([a-z])=(.*)/);
if (matches) {
if (matches[1] == 'm') {
markerString = matches[2];
} else {
return false;
}
} else {
layerString = component;
}
}
if (this.layerSwitcher) {
this.layerSwitcher.setURLString(layerString);
}
return true;
}
if (this.layerSwitcher) {
this.layerSwitcher.setURLString("");
}
return false;
}
_updateHash() {
try {
window.history.replaceState(
window.history.state,
'',
this.getHashString(),
);
} catch (e) {
console.log(e);
}
}
getHashString() {
const center = this._map.getCenter(),
zoom = Math.round(this._map.getZoom() * 100) / 100,
// derived from equation: 512px * 2^z / 360 / 10^d < 0.5px
precision = Math.ceil(
(zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10,
),
m = Math.pow(10, precision),
lng = Math.round(center.lng * m) / m,
lat = Math.round(center.lat * m) / m,
bearing = this._map.getBearing(),
pitch = this._map.getPitch();
let hash = `#${zoom}/${lat}/${lng}`;
let layers = null;
if (this.layerSwitcher) {
layers = this.layerSwitcher.getURLString();
}
if (layers) {
hash += '/' + layers;
}
return hash;
}
init(options) {
options['hash'] = false;
const loc = window.location.hash.replace('#', '').split('/');
if (loc.length >= 3) {
options['center'] = [+loc[2], +loc[1]];
options['zoom'] = +loc[0];
}
return options;
}
};
export default URLHash;