]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/leaflet.map.js
Initalise the MiniMaps only when the style is acually needed
[rails.git] / app / assets / javascripts / leaflet.map.js
1 //= require download_util
2 L.extend(L.LatLngBounds.prototype, {
3   getSize: function () {
4     return (this._northEast.lat - this._southWest.lat) *
5            (this._northEast.lng - this._southWest.lng);
6   }
7 });
8
9 L.OSM.Map = L.Map.extend({
10   initialize: function (id, options) {
11     L.Map.prototype.initialize.call(this, id, options);
12
13     this.baseLayers = OSM.LAYER_DEFINITIONS.map((
14       { credit, nameId, leafletOsmId, leafletOsmDarkId, style, styleDark, ...layerOptions }
15     ) => {
16       if (credit) layerOptions.attribution = makeAttribution(credit);
17       if (nameId) layerOptions.name = OSM.i18n.t(`javascripts.map.base.${nameId}`);
18
19       let layerConstructor;
20       if (OSM.isDarkMap()) {
21         layerConstructor = L.OSM[leafletOsmDarkId] ?? L.OSM[leafletOsmId] ?? L.OSM.TileLayer;
22         layerOptions.url = layerOptions.urlDark ?? layerOptions.url;
23       } else {
24         layerConstructor = L.OSM[leafletOsmId] ?? L.OSM.TileLayer;
25       }
26
27       layerOptions.url = layerOptions.url?.replace("{ratio}", "{r}");
28
29       const layer = new layerConstructor(layerOptions);
30       layer.on("add", () => {
31         this.fire("baselayerchange", { layer: layer });
32       });
33       layer.options.style = (OSM.isDarkMap() && styleDark) || style;
34       return layer;
35     });
36
37     this.noteLayer = new L.FeatureGroup();
38     this.noteLayer.options = { code: "N" };
39
40     this.dataLayer = new L.OSM.DataLayer(null);
41     this.dataLayer.options.code = "D";
42
43     this.gpsLayer = new L.OSM.GPS({
44       pane: "overlayPane",
45       code: "G"
46     });
47     this.gpsLayer.on("add", () => {
48       this.fire("overlayadd", { layer: this.gpsLayer });
49     }).on("remove", () => {
50       this.fire("overlayremove", { layer: this.gpsLayer });
51     });
52
53     this.on("baselayerchange", function (event) {
54       if (this.baseLayers.indexOf(event.layer) >= 0) {
55         this.setMaxZoom(event.layer.options.maxZoom);
56       }
57     });
58
59     function makeAttribution(credit) {
60       let attribution = "";
61
62       attribution += OSM.i18n.t("javascripts.map.copyright_text", {
63         copyright_link: $("<a>", {
64           href: "/copyright",
65           text: OSM.i18n.t("javascripts.map.openstreetmap_contributors")
66         }).prop("outerHTML")
67       });
68
69       attribution += credit.donate ? " ♥️ " : ". ";
70       attribution += makeCredit(credit);
71       attribution += ". ";
72
73       attribution += $("<a>", {
74         href: "https://wiki.osmfoundation.org/wiki/Terms_of_Use",
75         text: OSM.i18n.t("javascripts.map.website_and_api_terms")
76       }).prop("outerHTML");
77
78       return attribution;
79     }
80
81     function makeCredit(credit) {
82       const children = {};
83       for (const childId in credit.children) {
84         children[childId] = makeCredit(credit.children[childId]);
85       }
86       const text = OSM.i18n.t(`javascripts.map.${credit.id}`, children);
87       if (credit.href) {
88         const link = $("<a>", {
89           href: credit.href,
90           text: text
91         });
92         if (credit.donate) {
93           link.addClass("donate-attr");
94         } else {
95           link.attr("target", "_blank");
96         }
97         return link.prop("outerHTML");
98       }
99       return text;
100     }
101   },
102
103   updateLayers: function (layerParam) {
104     const oldBaseLayer = this.getMapBaseLayer();
105     let newBaseLayer;
106
107     for (const layer of this.baseLayers) {
108       if (!newBaseLayer || layerParam.includes(layer.options.code)) {
109         newBaseLayer = layer;
110       }
111     }
112
113     if (newBaseLayer !== oldBaseLayer) {
114       if (oldBaseLayer) this.removeLayer(oldBaseLayer);
115       if (newBaseLayer) this.addLayer(newBaseLayer);
116     }
117   },
118
119   getLayersCode: function () {
120     let layerConfig = "";
121     this.eachLayer(function (layer) {
122       if (layer.options && layer.options.code) {
123         layerConfig += layer.options.code;
124       }
125     });
126     return layerConfig;
127   },
128
129   getMapBaseLayerId: function () {
130     const layer = this.getMapBaseLayer();
131     if (layer) return layer.options.layerId;
132   },
133
134   getMapBaseLayer: function () {
135     for (const layer of this.baseLayers) {
136       if (this.hasLayer(layer)) return layer;
137     }
138   },
139
140   getUrl: function (marker) {
141     const params = {};
142
143     if (marker && this.hasLayer(marker)) {
144       [params.mlat, params.mlon] = OSM.cropLocation(marker.getLatLng(), this.getZoom());
145     }
146
147     let url = location.protocol + "//" + OSM.SERVER_URL + "/";
148     const query = new URLSearchParams(params),
149           hash = OSM.formatHash(this);
150
151     if (query) url += "?" + query;
152     if (hash) url += hash;
153
154     return url;
155   },
156
157   getShortUrl: function (marker) {
158     const zoom = this.getZoom(),
159           latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
160           char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
161           x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
162           y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
163           // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
164           // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
165           // and drops the last 4 bits of the full 64 bit Morton code.
166           c1 = interlace(x >>> 17, y >>> 17),
167           c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff);
168     let str = location.protocol + "//" + location.hostname.replace(/^www\.openstreetmap\.org/i, "osm.org") + "/go/";
169
170     for (let i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
171       const digit = (c1 >> (24 - (6 * i))) & 0x3f;
172       str += char_array.charAt(digit);
173     }
174     for (let i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
175       const digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
176       str += char_array.charAt(digit);
177     }
178     for (let i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
179
180     // Called to interlace the bits in x and y, making a Morton code.
181     function interlace(x, y) {
182       let interlaced_x = x,
183           interlaced_y = y;
184       interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
185       interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
186       interlaced_x = (interlaced_x | (interlaced_x << 2)) & 0x33333333;
187       interlaced_x = (interlaced_x | (interlaced_x << 1)) & 0x55555555;
188       interlaced_y = (interlaced_y | (interlaced_y << 8)) & 0x00ff00ff;
189       interlaced_y = (interlaced_y | (interlaced_y << 4)) & 0x0f0f0f0f;
190       interlaced_y = (interlaced_y | (interlaced_y << 2)) & 0x33333333;
191       interlaced_y = (interlaced_y | (interlaced_y << 1)) & 0x55555555;
192       return (interlaced_x << 1) | interlaced_y;
193     }
194
195     const params = new URLSearchParams();
196     const layers = this.getLayersCode().replace("M", "");
197
198     if (layers) {
199       params.set("layers", layers);
200     }
201
202     if (marker && this.hasLayer(marker)) {
203       params.set("m", "");
204     }
205
206     if (this._object) {
207       params.set(this._object.type, this._object.id);
208     }
209
210     const query = params.toString();
211     if (query) {
212       str += "?" + query;
213     }
214
215     return str;
216   },
217
218   getGeoUri: function (marker) {
219     let latLng = this.getCenter();
220     const zoom = this.getZoom();
221
222     if (marker && this.hasLayer(marker)) {
223       latLng = marker.getLatLng();
224     }
225
226     return `geo:${OSM.cropLocation(latLng, zoom).join(",")}?z=${zoom}`;
227   },
228
229   addObject: function (object, callback) {
230     class ElementGoneError extends Error {
231       constructor(message = "Element is gone") {
232         super(message);
233         this.name = "ElementGoneError";
234       }
235     }
236
237     const objectStyle = {
238       color: "#FF6200",
239       weight: 4,
240       opacity: 1,
241       fillOpacity: 0.5
242     };
243
244     const changesetStyle = {
245       weight: 4,
246       color: "#FF9500",
247       opacity: 1,
248       fillOpacity: 0,
249       interactive: false
250     };
251
252     const haloStyle = {
253       weight: 2.5,
254       radius: 20,
255       fillOpacity: 0.5,
256       color: "#FF6200"
257     };
258
259     this.removeObject();
260
261     if (object.type === "note" || object.type === "changeset") {
262       this._objectLoader = { abort: () => {} };
263
264       this._object = object;
265       this._objectLayer = L.featureGroup().addTo(this);
266
267       if (object.type === "note") {
268         L.circleMarker(object.latLng, haloStyle).addTo(this._objectLayer);
269
270         if (object.icon) {
271           L.marker(object.latLng, {
272             icon: object.icon,
273             opacity: 1,
274             interactive: true
275           }).addTo(this._objectLayer);
276         }
277       } else if (object.type === "changeset") {
278         if (object.bbox) {
279           L.rectangle([
280             [object.bbox.minlat, object.bbox.minlon],
281             [object.bbox.maxlat, object.bbox.maxlon]
282           ], changesetStyle).addTo(this._objectLayer);
283         }
284       }
285
286       if (callback) callback(this._objectLayer.getBounds());
287       this.fire("overlayadd", { layer: this._objectLayer });
288     } else { // element handled by L.OSM.DataLayer
289       const map = this;
290       this._objectLoader = new AbortController();
291       fetch(OSM.apiUrl(object), {
292         headers: { accept: "application/json", ...OSM.oauth },
293         signal: this._objectLoader.signal
294       })
295         .then(async response => {
296           if (response.ok) {
297             return response.json();
298           }
299
300           if (response.status === 410) {
301             throw new ElementGoneError();
302           }
303
304           const status = response.statusText || response.status;
305           if (response.status !== 400 && response.status !== 509) {
306             throw new Error(status);
307           }
308
309           const text = await response.text();
310           throw new Error(text || status);
311         })
312         .then(function (data) {
313           const visible_data = {
314             ...data,
315             elements: data.elements?.filter(el => el.visible !== false) ?? []
316           };
317
318           map._object = object;
319
320           map._objectLayer = new L.OSM.DataLayer(null, {
321             styles: {
322               node: objectStyle,
323               way: objectStyle,
324               area: objectStyle,
325               changeset: changesetStyle
326             }
327           });
328
329           map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
330             return object.type === "node" ||
331                    (object.type === "relation" && Boolean(relationNodes[node.id]));
332           };
333
334           map._objectLayer.addData(visible_data);
335           map._objectLayer.addTo(map);
336
337           if (callback) callback(map._objectLayer.getBounds());
338           map.fire("overlayadd", { layer: map._objectLayer });
339           $("#browse_status").empty();
340         })
341         .catch(function (error) {
342           if (error.name === "AbortError") return;
343           if (error instanceof ElementGoneError) {
344             $("#browse_status").empty();
345             return;
346           }
347           OSM.displayLoadError(error?.message, () => {
348             $("#browse_status").empty();
349           });
350         });
351     }
352   },
353
354   removeObject: function () {
355     this._object = null;
356     if (this._objectLoader) this._objectLoader.abort();
357     if (this._objectLayer) this.removeLayer(this._objectLayer);
358     this.fire("overlayremove", { layer: this._objectLayer });
359   },
360
361   getState: function () {
362     return {
363       center: this.getCenter().wrap(),
364       zoom: this.getZoom(),
365       layers: this.getLayersCode()
366     };
367   },
368
369   setState: function (state, options) {
370     if (state.center) this.setView(state.center, state.zoom, options);
371     if (state.layers) this.updateLayers(state.layers);
372   },
373
374   setSidebarOverlaid: function (overlaid) {
375     const mediumDeviceWidth = window.getComputedStyle(document.documentElement).getPropertyValue("--bs-breakpoint-md");
376     const isMediumDevice = window.matchMedia(`(max-width: ${mediumDeviceWidth})`).matches;
377     const sidebarWidth = $("#sidebar").width();
378     const sidebarHeight = $("#sidebar").height();
379     if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
380       $("#content").addClass("overlay-sidebar");
381       this.invalidateSize({ pan: false });
382       if (isMediumDevice) {
383         this.panBy([0, -sidebarHeight], { animate: false });
384       } else if ($("html").attr("dir") !== "rtl") {
385         this.panBy([-sidebarWidth, 0], { animate: false });
386       }
387     } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
388       if (isMediumDevice) {
389         this.panBy([0, $("#map").height() / 2], { animate: false });
390       } else if ($("html").attr("dir") !== "rtl") {
391         this.panBy([sidebarWidth, 0], { animate: false });
392       }
393       $("#content").removeClass("overlay-sidebar");
394       this.invalidateSize({ pan: false });
395     }
396     return this;
397   }
398 });
399
400 OSM.isDarkMap = function () {
401   const mapTheme = $("body").attr("data-map-theme");
402   if (mapTheme) return mapTheme === "dark";
403   return window.matchMedia("(prefers-color-scheme: dark)").matches;
404 };
405
406 OSM.getMarker = function ({ icon = "dot", color = "var(--marker-red)", ...options }) {
407   const html = `<svg viewBox="0 0 25 40" class="pe-none" overflow="visible"><use href="#pin-shadow" /><use href="#pin-${icon}" color="${color}" class="pe-auto" /></svg>`;
408   return L.divIcon({
409     ...options,
410     html,
411     iconSize: [25, 40],
412     iconAnchor: [12.5, 40],
413     popupAnchor: [1, -34]
414   });
415 };
416
417 OSM.noteMarkers = {
418   "closed": OSM.getMarker({ icon: "tick", color: "var(--marker-green)" }),
419   "new": OSM.getMarker({ icon: "plus", color: "var(--marker-blue)" }),
420   "open": OSM.getMarker({ icon: "cross", color: "var(--marker-red)" })
421 };