]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Include L.Control.Locate from L.OSM.locate
[rails.git] / app / assets / javascripts / index.js
1 //= require_self
2 //= require leaflet.sidebar
3 //= require leaflet.sidebar-pane
4 //= require leaflet.locate
5 //= require leaflet.layers
6 //= require leaflet.key
7 //= require leaflet.note
8 //= require leaflet.share
9 //= require leaflet.polyline
10 //= require leaflet.query
11 //= require leaflet.contextmenu
12 //= require index/contextmenu
13 //= require index/search
14 //= require index/layers/data
15 //= require index/export
16 //= require index/layers/notes
17 //= require index/history
18 //= require index/note
19 //= require index/new_note
20 //= require index/directions
21 //= require index/changeset
22 //= require index/query
23 //= require index/home
24 //= require router
25
26 $(function () {
27   const map = new L.OSM.Map("map", {
28     zoomControl: false,
29     layerControl: false,
30     contextmenu: true,
31     worldCopyJump: true
32   });
33
34   OSM.loadSidebarContent = function (path, callback) {
35     let content_path = path;
36
37     map.setSidebarOverlaid(false);
38
39     $("#sidebar_loader").prop("hidden", false).addClass("delayed-fade-in");
40
41     // Prevent caching the XHR response as a full-page URL
42     // https://github.com/openstreetmap/openstreetmap-website/issues/5663
43     if (content_path.indexOf("?") >= 0) {
44       content_path += "&xhr=1";
45     } else {
46       content_path += "?xhr=1";
47     }
48
49     $("#sidebar_content")
50       .empty();
51
52     fetch(content_path, { headers: { "accept": "text/html", "x-requested-with": "XMLHttpRequest" } })
53       .then(response => {
54         $("#flash").empty();
55         $("#sidebar_loader").removeClass("delayed-fade-in").prop("hidden", true);
56
57         const title = response.headers.get("X-Page-Title");
58         if (title) document.title = decodeURIComponent(title);
59
60         return response.text();
61       })
62       .then(html => {
63         const content = $(html);
64
65         $("head")
66           .find("link[type=\"application/atom+xml\"]")
67           .remove();
68
69         $("head")
70           .append(content.filter("link[type=\"application/atom+xml\"]"));
71
72         $("#sidebar_content").html(content.not("link[type=\"application/atom+xml\"]"));
73
74         if (callback) {
75           callback();
76         }
77       });
78   };
79
80   const token = $("head").data("oauthToken");
81   if (token) OSM.oauth = { authorization: "Bearer " + token };
82
83   const params = OSM.mapParams();
84
85   map.attributionControl.setPrefix("");
86
87   map.updateLayers(params.layers);
88
89   map.on("baselayerchange", function (e) {
90     if (map.getZoom() > e.layer.options.maxZoom) {
91       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
92     }
93   });
94
95   const sidebar = L.OSM.sidebar("#map-ui")
96     .addTo(map);
97
98   const position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
99
100   function addControlGroup(controls) {
101     for (const control of controls) control.addTo(map);
102
103     const firstContainer = controls[0].getContainer();
104     $(firstContainer).find(".control-button").first()
105       .addClass("control-button-first");
106
107     const lastContainer = controls[controls.length - 1].getContainer();
108     $(lastContainer).find(".control-button").last()
109       .addClass("control-button-last");
110   }
111
112   addControlGroup([
113     L.OSM.zoom({ position: position }),
114     L.OSM.locate({ position: position })
115   ]);
116
117   addControlGroup([
118     L.OSM.layers({
119       position: position,
120       layers: map.baseLayers,
121       sidebar: sidebar
122     }),
123     L.OSM.key({
124       position: position,
125       sidebar: sidebar
126     }),
127     L.OSM.share({
128       "position": position,
129       "sidebar": sidebar,
130       "short": true
131     })
132   ]);
133
134   addControlGroup([
135     L.OSM.note({
136       position: position,
137       sidebar: sidebar
138     })
139   ]);
140
141   addControlGroup([
142     L.OSM.query({
143       position: position,
144       sidebar: sidebar
145     })
146   ]);
147
148   L.control.scale()
149     .addTo(map);
150
151   OSM.initializeContextMenu(map);
152
153   if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
154     OSM.initializeNotesLayer(map);
155     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
156       map.addLayer(map.noteLayer);
157     }
158
159     OSM.initializeDataLayer(map);
160     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
161       map.addLayer(map.dataLayer);
162     }
163
164     if (params.layers.indexOf(map.gpsLayer.options.code) >= 0) {
165       map.addLayer(map.gpsLayer);
166     }
167   }
168
169   $(".leaflet-control .control-button").tooltip({ placement: "left", container: "body" });
170
171   const expiry = new Date();
172   expiry.setYear(expiry.getFullYear() + 10);
173
174   map.on("moveend baselayerchange overlayadd overlayremove", function () {
175     updateLinks(
176       map.getCenter().wrap(),
177       map.getZoom(),
178       map.getLayersCode(),
179       map._object);
180
181     Cookies.set("_osm_location", OSM.locationCookie(map), { secure: true, expires: expiry, path: "/", samesite: "lax" });
182   });
183
184   if (Cookies.get("_osm_welcome") !== "hide") {
185     $(".welcome").removeAttr("hidden");
186   }
187
188   $(".welcome .btn-close").on("click", function () {
189     $(".welcome").hide();
190     Cookies.set("_osm_welcome", "hide", { secure: true, expires: expiry, path: "/", samesite: "lax" });
191   });
192
193   const bannerExpiry = new Date();
194   bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
195
196   $("#banner .btn-close").on("click", function (e) {
197     const cookieId = e.target.id;
198     $("#banner").hide();
199     e.preventDefault();
200     if (cookieId) {
201       Cookies.set(cookieId, "hide", { secure: true, expires: bannerExpiry, path: "/", samesite: "lax" });
202     }
203   });
204
205   if (OSM.MATOMO) {
206     map.on("baselayerchange overlayadd", function (e) {
207       if (e.layer.options) {
208         const goal = OSM.MATOMO.goals[e.layer.options.layerId];
209
210         if (goal) {
211           $("body").trigger("matomogoal", goal);
212         }
213       }
214     });
215   }
216
217   if (params.bounds) {
218     map.fitBounds(params.bounds);
219   } else {
220     map.setView([params.lat, params.lon], params.zoom);
221   }
222
223   if (params.marker) {
224     L.marker([params.mlat, params.mlon]).addTo(map);
225   }
226
227   function remoteEditHandler(bbox, object) {
228     const remoteEditHost = "http://127.0.0.1:8111",
229           osmHost = location.protocol + "//" + location.host,
230           query = new URLSearchParams({
231             left: bbox.getWest() - 0.0001,
232             top: bbox.getNorth() + 0.0001,
233             right: bbox.getEast() + 0.0001,
234             bottom: bbox.getSouth() - 0.0001
235           });
236
237     if (object && object.type !== "note") query.set("select", object.type + object.id); // can't select notes
238     sendRemoteEditCommand(remoteEditHost + "/load_and_zoom?" + query)
239       .then(() => {
240         if (object && object.type === "note") {
241           const noteQuery = new URLSearchParams({ url: osmHost + OSM.apiUrl(object) });
242           sendRemoteEditCommand(remoteEditHost + "/import?" + noteQuery);
243         }
244       })
245       .catch(() => {
246         // eslint-disable-next-line no-alert
247         alert(OSM.i18n.t("site.index.remote_failed"));
248       });
249
250     function sendRemoteEditCommand(url) {
251       return fetch(url, { mode: "no-cors", signal: AbortSignal.timeout(5000) });
252     }
253
254     return false;
255   }
256
257   $("a[data-editor=remote]").click(function (e) {
258     const params = OSM.mapParams(this.search);
259     remoteEditHandler(map.getBounds(), params.object);
260     e.preventDefault();
261   });
262
263   if (new URLSearchParams(location.search).get("edit_help")) {
264     $("#editanchor")
265       .removeAttr("title")
266       .tooltip({
267         placement: "bottom",
268         title: OSM.i18n.t("javascripts.edit_help")
269       })
270       .tooltip("show");
271
272     $("body").one("click", function () {
273       $("#editanchor").tooltip("hide");
274     });
275   }
276
277   OSM.Index = function (map) {
278     const page = {};
279
280     page.pushstate = page.popstate = function () {
281       map.setSidebarOverlaid(true);
282       document.title = OSM.i18n.t("layouts.project_name.title");
283     };
284
285     page.load = function () {
286       const params = new URLSearchParams(location.search);
287       if (params.has("query")) {
288         $("#sidebar .search_form input[name=query]").value(params.get("query"));
289       }
290       if (!("autofocus" in document.createElement("input"))) {
291         $("#sidebar .search_form input[name=query]").focus();
292       }
293       return map.getState();
294     };
295
296     return page;
297   };
298
299   OSM.Browse = function (map, type) {
300     const page = {};
301
302     page.pushstate = page.popstate = function (path, id, version) {
303       OSM.loadSidebarContent(path, function () {
304         addObject(type, id, version);
305       });
306     };
307
308     page.load = function (path, id, version) {
309       addObject(type, id, version, true);
310     };
311
312     function addObject(type, id, version, center) {
313       const hashParams = OSM.parseHash();
314       map.addObject({ type: type, id: parseInt(id, 10), version: version && parseInt(version, 10) }, function (bounds) {
315         if (!hashParams.center && bounds.isValid() &&
316             (center || !map.getBounds().contains(bounds))) {
317           OSM.router.withoutMoveListener(function () {
318             map.fitBounds(bounds);
319           });
320         }
321       });
322     }
323
324     page.unload = function () {
325       map.removeObject();
326     };
327
328     return page;
329   };
330
331   OSM.OldBrowse = function () {
332     const page = {};
333
334     page.pushstate = page.popstate = function (path) {
335       OSM.loadSidebarContent(path);
336     };
337
338     return page;
339   };
340
341   const history = OSM.History(map);
342
343   OSM.router = OSM.Router(map, {
344     "/": OSM.Index(map),
345     "/search": OSM.Search(map),
346     "/directions": OSM.Directions(map),
347     "/export": OSM.Export(map),
348     "/note/new": OSM.NewNote(map),
349     "/history/friends": history,
350     "/history/nearby": history,
351     "/history": history,
352     "/user/:display_name/history": history,
353     "/note/:id": OSM.Note(map),
354     "/node/:id(/history)": OSM.Browse(map, "node"),
355     "/node/:id/history/:version": OSM.Browse(map, "node"),
356     "/way/:id(/history)": OSM.Browse(map, "way"),
357     "/way/:id/history/:version": OSM.OldBrowse(),
358     "/relation/:id(/history)": OSM.Browse(map, "relation"),
359     "/relation/:id/history/:version": OSM.OldBrowse(),
360     "/changeset/:id": OSM.Changeset(map),
361     "/query": OSM.Query(map),
362     "/account/home": OSM.Home(map)
363   });
364
365   if (OSM.preferred_editor === "remote" && location.pathname === "/edit") {
366     remoteEditHandler(map.getBounds(), params.object);
367     OSM.router.setCurrentPath("/");
368   }
369
370   OSM.router.load();
371
372   $(document).on("click", "a", function (e) {
373     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
374       return;
375     }
376
377     // Open links in a new tab as normal.
378     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
379       return;
380     }
381
382     // Open local anchor links as normal.
383     if ($(this).attr("href")?.startsWith("#")) {
384       return;
385     }
386
387     // Ignore cross-protocol and cross-origin links.
388     if (location.protocol !== this.protocol || location.host !== this.host) {
389       return;
390     }
391
392     if (OSM.router.route(this.pathname + this.search + this.hash)) {
393       e.preventDefault();
394       if (this.pathname !== "/directions") {
395         $("header").addClass("closed");
396       }
397     }
398   });
399
400   $(document).on("click", "#sidebar .sidebar-close-controls button", function () {
401     OSM.router.route("/" + OSM.formatHash(map));
402   });
403 });