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