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