]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/leaflet.map.js
Merge remote-tracking branch 'upstream/pull/5809'
[rails.git] / app / assets / javascripts / leaflet.map.js
1 L.extend(L.LatLngBounds.prototype, {
2   getSize: function () {
3     return (this._northEast.lat - this._southWest.lat) *
4            (this._northEast.lng - this._southWest.lng);
5   },
6
7   wrap: function () {
8     return new L.LatLngBounds(this._southWest.wrap(), this._northEast.wrap());
9   }
10 });
11
12 L.OSM.Map = L.Map.extend({
13   initialize: function (id, options) {
14     L.Map.prototype.initialize.call(this, id, options);
15
16     this.baseLayers = [];
17
18     for (const layerDefinition of OSM.LAYER_DEFINITIONS) {
19       let layerConstructor = L.OSM.TileLayer;
20       const layerOptions = {};
21
22       for (const [property, value] of Object.entries(layerDefinition)) {
23         if (property === "credit") {
24           layerOptions.attribution = makeAttribution(value);
25         } else if (property === "nameId") {
26           layerOptions.name = I18n.t(`javascripts.map.base.${value}`);
27         } else if (property === "leafletOsmId") {
28           layerConstructor = L.OSM[value];
29         } else if (property === "leafletOsmDarkId" && OSM.isDarkMap() && L.OSM[value]) {
30           layerConstructor = L.OSM[value];
31         } else {
32           layerOptions[property] = value;
33         }
34       }
35
36       const layer = new layerConstructor(layerOptions);
37       layer.on("add", () => {
38         this.fire("baselayerchange", { layer: layer });
39       });
40       this.baseLayers.push(layer);
41     }
42
43     this.noteLayer = new L.FeatureGroup();
44     this.noteLayer.options = { code: "N" };
45
46     this.dataLayer = new L.OSM.DataLayer(null, { asynchronous: true });
47     this.dataLayer.options.code = "D";
48
49     this.gpsLayer = new L.OSM.GPS({
50       pane: "overlayPane",
51       code: "G"
52     });
53     this.gpsLayer.on("add", () => {
54       this.fire("overlayadd", { layer: this.gpsLayer });
55     }).on("remove", () => {
56       this.fire("overlayremove", { layer: this.gpsLayer });
57     });
58
59
60     this.on("baselayerchange", function (event) {
61       if (this.baseLayers.indexOf(event.layer) >= 0) {
62         this.setMaxZoom(event.layer.options.maxZoom);
63       }
64     });
65
66     function makeAttribution(credit) {
67       let attribution = "";
68
69       attribution += I18n.t("javascripts.map.copyright_text", {
70         copyright_link: $("<a>", {
71           href: "/copyright",
72           text: I18n.t("javascripts.map.openstreetmap_contributors")
73         }).prop("outerHTML")
74       });
75
76       attribution += credit.donate ? " &hearts; " : ". ";
77       attribution += makeCredit(credit);
78       attribution += ". ";
79
80       attribution += $("<a>", {
81         href: "https://wiki.osmfoundation.org/wiki/Terms_of_Use",
82         text: I18n.t("javascripts.map.website_and_api_terms")
83       }).prop("outerHTML");
84
85       return attribution;
86     }
87
88     function makeCredit(credit) {
89       const children = {};
90       for (const childId in credit.children) {
91         children[childId] = makeCredit(credit.children[childId]);
92       }
93       const text = I18n.t(`javascripts.map.${credit.id}`, children);
94       if (credit.href) {
95         const link = $("<a>", {
96           href: credit.href,
97           text: text
98         });
99         if (credit.donate) {
100           link.addClass("donate-attr");
101         } else {
102           link.attr("target", "_blank");
103         }
104         return link.prop("outerHTML");
105       }
106       return text;
107     }
108   },
109
110   updateLayers: function (layerParam) {
111     const oldBaseLayer = this.getMapBaseLayer();
112     let newBaseLayer;
113
114     for (const layer of this.baseLayers) {
115       if (!newBaseLayer || layerParam.includes(layer.options.code)) {
116         newBaseLayer = layer;
117       }
118     }
119
120     if (newBaseLayer !== oldBaseLayer) {
121       if (oldBaseLayer) this.removeLayer(oldBaseLayer);
122       if (newBaseLayer) this.addLayer(newBaseLayer);
123     }
124   },
125
126   getLayersCode: function () {
127     let layerConfig = "";
128     this.eachLayer(function (layer) {
129       if (layer.options && layer.options.code) {
130         layerConfig += layer.options.code;
131       }
132     });
133     return layerConfig;
134   },
135
136   getMapBaseLayerId: function () {
137     const layer = this.getMapBaseLayer();
138     if (layer) return layer.options.layerId;
139   },
140
141   getMapBaseLayer: function () {
142     for (const layer of this.baseLayers) {
143       if (this.hasLayer(layer)) return layer;
144     }
145   },
146
147   getUrl: function (marker) {
148     const params = {};
149
150     if (marker && this.hasLayer(marker)) {
151       [params.mlat, params.mlon] = OSM.cropLocation(marker.getLatLng(), this.getZoom());
152     }
153
154     let url = location.protocol + "//" + OSM.SERVER_URL + "/";
155     const query = new URLSearchParams(params),
156           hash = OSM.formatHash(this);
157
158     if (query) url += "?" + query;
159     if (hash) url += hash;
160
161     return url;
162   },
163
164   getShortUrl: function (marker) {
165     const zoom = this.getZoom(),
166           latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
167           char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
168           x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
169           y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
170           // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
171           // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
172           // and drops the last 4 bits of the full 64 bit Morton code.
173           c1 = interlace(x >>> 17, y >>> 17),
174           c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff);
175     let str = location.protocol + "//" + location.hostname.replace(/^www\.openstreetmap\.org/i, "osm.org") + "/go/";
176
177     for (let i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
178       const digit = (c1 >> (24 - (6 * i))) & 0x3f;
179       str += char_array.charAt(digit);
180     }
181     for (let i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
182       const digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
183       str += char_array.charAt(digit);
184     }
185     for (let i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
186
187     // Called to interlace the bits in x and y, making a Morton code.
188     function interlace(x, y) {
189       let interlaced_x = x,
190           interlaced_y = y;
191       interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
192       interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
193       interlaced_x = (interlaced_x | (interlaced_x << 2)) & 0x33333333;
194       interlaced_x = (interlaced_x | (interlaced_x << 1)) & 0x55555555;
195       interlaced_y = (interlaced_y | (interlaced_y << 8)) & 0x00ff00ff;
196       interlaced_y = (interlaced_y | (interlaced_y << 4)) & 0x0f0f0f0f;
197       interlaced_y = (interlaced_y | (interlaced_y << 2)) & 0x33333333;
198       interlaced_y = (interlaced_y | (interlaced_y << 1)) & 0x55555555;
199       return (interlaced_x << 1) | interlaced_y;
200     }
201
202     const params = new URLSearchParams();
203     const layers = this.getLayersCode().replace("M", "");
204
205     if (layers) {
206       params.set("layers", layers);
207     }
208
209     if (marker && this.hasLayer(marker)) {
210       params.set("m", "");
211     }
212
213     if (this._object) {
214       params.set(this._object.type, this._object.id);
215     }
216
217     const query = params.toString();
218     if (query) {
219       str += "?" + query;
220     }
221
222     return str;
223   },
224
225   getGeoUri: function (marker) {
226     let latLng = this.getCenter();
227     const zoom = this.getZoom();
228
229     if (marker && this.hasLayer(marker)) {
230       latLng = marker.getLatLng();
231     }
232
233     return `geo:${OSM.cropLocation(latLng, zoom).join(",")}?z=${zoom}`;
234   },
235
236   addObject: function (object, callback) {
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" },
293         signal: this._objectLoader.signal
294       })
295         .then(response => response.json())
296         .then(function (data) {
297           map._object = object;
298
299           map._objectLayer = new L.OSM.DataLayer(null, {
300             styles: {
301               node: objectStyle,
302               way: objectStyle,
303               area: objectStyle,
304               changeset: changesetStyle
305             }
306           });
307
308           map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
309             return object.type === "node" ||
310                    (object.type === "relation" && Boolean(relationNodes[node.id]));
311           };
312
313           map._objectLayer.addData(data);
314           map._objectLayer.addTo(map);
315
316           if (callback) callback(map._objectLayer.getBounds());
317           map.fire("overlayadd", { layer: map._objectLayer });
318         })
319         .catch(() => {});
320     }
321   },
322
323   removeObject: function () {
324     this._object = null;
325     if (this._objectLoader) this._objectLoader.abort();
326     if (this._objectLayer) this.removeLayer(this._objectLayer);
327     this.fire("overlayremove", { layer: this._objectLayer });
328   },
329
330   getState: function () {
331     return {
332       center: this.getCenter().wrap(),
333       zoom: this.getZoom(),
334       layers: this.getLayersCode()
335     };
336   },
337
338   setState: function (state, options) {
339     if (state.center) this.setView(state.center, state.zoom, options);
340     if (state.layers) this.updateLayers(state.layers);
341   },
342
343   setSidebarOverlaid: function (overlaid) {
344     const mediumDeviceWidth = window.getComputedStyle(document.documentElement).getPropertyValue("--bs-breakpoint-md");
345     const isMediumDevice = window.matchMedia(`(max-width: ${mediumDeviceWidth})`).matches;
346     const sidebarWidth = $("#sidebar").width();
347     const sidebarHeight = $("#sidebar").height();
348     if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
349       $("#content").addClass("overlay-sidebar");
350       this.invalidateSize({ pan: false });
351       if (isMediumDevice) {
352         this.panBy([0, -sidebarHeight], { animate: false });
353       } else if ($("html").attr("dir") !== "rtl") {
354         this.panBy([-sidebarWidth, 0], { animate: false });
355       }
356     } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
357       if (isMediumDevice) {
358         this.panBy([0, $("#map").height() / 2], { animate: false });
359       } else if ($("html").attr("dir") !== "rtl") {
360         this.panBy([sidebarWidth, 0], { animate: false });
361       }
362       $("#content").removeClass("overlay-sidebar");
363       this.invalidateSize({ pan: false });
364     }
365     return this;
366   }
367 });
368
369 L.Icon.Default.imagePath = "/images/";
370
371 L.Icon.Default.imageUrls = {
372   "/images/marker-icon.png": OSM.MARKER_ICON,
373   "/images/marker-icon-2x.png": OSM.MARKER_ICON_2X,
374   "/images/marker-shadow.png": OSM.MARKER_SHADOW
375 };
376
377 L.extend(L.Icon.Default.prototype, {
378   _oldGetIconUrl: L.Icon.Default.prototype._getIconUrl,
379
380   _getIconUrl: function (name) {
381     const url = this._oldGetIconUrl(name);
382     return L.Icon.Default.imageUrls[url];
383   }
384 });
385
386 OSM.isDarkMap = function () {
387   const mapTheme = $("body").attr("data-map-theme");
388   if (mapTheme) return mapTheme === "dark";
389   const siteTheme = $("html").attr("data-bs-theme");
390   if (siteTheme) return siteTheme === "dark";
391   return window.matchMedia("(prefers-color-scheme: dark)").matches;
392 };
393
394 OSM.getUserIcon = function (url) {
395   return L.icon({
396     iconUrl: url || OSM.MARKER_RED,
397     iconSize: [25, 41],
398     iconAnchor: [12, 41],
399     popupAnchor: [1, -34],
400     shadowUrl: OSM.MARKER_SHADOW,
401     shadowSize: [41, 41]
402   });
403 };