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