-
Notifications
You must be signed in to change notification settings - Fork 0
/
ol-hash.js
40 lines (37 loc) · 1.05 KB
/
ol-hash.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
(function(ol) {
if (!ol || ol.hash) return;
var encode = function(view) {
var c = ol.proj.toLonLat(view.getCenter());
var z = view.getZoom();
var x = c[0].toFixed(6);
var y = c[1].toFixed(6);
return "#" + [z, y, x].join("/");
};
var decode = function(hash) {
var view = null;
if (hash.match(/^#([0-9]+)\/(.+)\/(.+)$/)) {
var z = parseInt(RegExp.$1);
var y = parseFloat(RegExp.$2);
var x = parseFloat(RegExp.$3);
if (!isNaN(y) && !isNaN(x)) {
view = new ol.View({
center: ol.proj.fromLonLat([x, y]),
zoom: z
});
}
}
return view;
};
ol.hash = function(map) {
var updateView = function() {
if (location.hash === encode(map.getView())) return;
var changedView = decode(location.hash);
if (changedView !== null) map.setView(changedView);
};
map.on("moveend", function(event) {
history.replaceState(null, null, encode(map.getView()));
});
updateView();
window.addEventListener("hashchange", updateView);
};
})(ol);