]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/id.js
Merge remote-tracking branch 'upstream/pull/7053'
[rails.git] / app / assets / javascripts / id.js
1 //= require @openstreetmap/id/dist/iD.js
2 //= require jquery.throttle-debounce
3
4 /* globals iD */
5
6 document.addEventListener("DOMContentLoaded", function () {
7   const container = document.getElementById("id-container");
8
9   if (typeof iD === "undefined" || !iD.utilDetect().support) {
10     container.innerHTML = "This editor is supported " +
11       "in Firefox, Chrome, Safari, Opera and Edge. " +
12       "Please upgrade your browser or use JOSM to edit the map.";
13     container.className = "unsupported";
14   } else {
15     const idContext = iD.coreContext();
16     idContext.connection().apiConnections([]);
17     const url = location.protocol + "//" + location.host;
18     idContext.preauth({
19       url: url,
20       apiUrl: url.replace("www.openstreetmap.org", "api.openstreetmap.org"),
21       access_token: container.dataset.token
22     });
23
24     const id = idContext
25       .embed(true)
26       .assetPath("@openstreetmap/id/dist/")
27       .assetMap(JSON.parse(container.dataset.assetMap))
28       .locale(container.dataset.locale)
29       .theme(container.dataset.theme)
30       .containerNode(container)
31       .init();
32
33     if (parent === window) {
34       // iD not opened in an iframe -> skip setting of parent  handlers
35       return;
36     }
37
38     function postMessageToParent(type, data) {
39       parent.postMessage({ type, data }, location.origin);
40     }
41
42     id.map().on("move.embed", window.Cowboy.throttle(250, function () {
43       if (id.inIntro()) return;
44       const zoom = ~~id.map().zoom(),
45             center = id.map().center(),
46             llz = { lon: center[0], lat: center[1], zoom: zoom };
47
48       postMessageToParent("hashchange", llz);
49     }));
50
51     window.addEventListener("message", function (event) {
52       if (event.source !== parent || event.origin !== location.origin) return;
53       const msg = event.data;
54       if (!msg || msg.type !== "hashchange") return;
55       const data = msg.data;
56       // 0ms timeout to avoid iframe JS context weirdness.
57       // https://gist.github.com/jfirebaugh/5439412
58       setTimeout(function () {
59         id.map().centerZoom(
60           [data.lon, data.lat],
61           Math.max(data.zoom || 15, 13));
62       }, 0);
63     });
64
65     new MutationObserver(() =>
66       postMessageToParent("titlechange", document.title)
67     ).observe(document.querySelector("title"), { childList: true, subtree: true, characterData: true });
68   }
69 });