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