]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/leaflet.map.js
Merge pull request #5591 from AntonKhorev/api-element-resources--index-paths
[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       } else {
110         return text;
111       }
112     }
113   },
114
115   updateLayers: function (layerParam) {
116     const oldBaseLayer = this.getMapBaseLayer();
117     let newBaseLayer;
118
119     for (const layer of this.baseLayers) {
120       if (!newBaseLayer || layerParam.includes(layer.options.code)) {
121         newBaseLayer = layer;
122       }
123     }
124
125     if (newBaseLayer !== oldBaseLayer) {
126       if (oldBaseLayer) this.removeLayer(oldBaseLayer);
127       if (newBaseLayer) this.addLayer(newBaseLayer);
128     }
129   },
130
131   getLayersCode: function () {
132     var layerConfig = "";
133     this.eachLayer(function (layer) {
134       if (layer.options && layer.options.code) {
135         layerConfig += layer.options.code;
136       }
137     });
138     return layerConfig;
139   },
140
141   getMapBaseLayerId: function () {
142     const layer = this.getMapBaseLayer();
143     if (layer) return layer.options.layerId;
144   },
145
146   getMapBaseLayer: function () {
147     for (const layer of this.baseLayers) {
148       if (this.hasLayer(layer)) return layer;
149     }
150   },
151
152   getUrl: function (marker) {
153     const params = {};
154
155     if (marker && this.hasLayer(marker)) {
156       [params.mlat, params.mlon] = OSM.cropLocation(marker.getLatLng(), this.getZoom());
157     }
158
159     var url = window.location.protocol + "//" + OSM.SERVER_URL + "/",
160         query = new URLSearchParams(params),
161         hash = OSM.formatHash(this);
162
163     if (query) url += "?" + query;
164     if (hash) url += hash;
165
166     return url;
167   },
168
169   getShortUrl: function (marker) {
170     var zoom = this.getZoom(),
171         latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
172         str = window.location.hostname.match(/^www\.openstreetmap\.org/i) ?
173           window.location.protocol + "//osm.org/go/" :
174           window.location.protocol + "//" + window.location.hostname + "/go/",
175         char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
176         x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
177         y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
178         // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
179         // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
180         // and drops the last 4 bits of the full 64 bit Morton code.
181         c1 = interlace(x >>> 17, y >>> 17), c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff),
182         digit,
183         i;
184
185     for (i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
186       digit = (c1 >> (24 - (6 * i))) & 0x3f;
187       str += char_array.charAt(digit);
188     }
189     for (i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
190       digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
191       str += char_array.charAt(digit);
192     }
193     for (i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
194
195     // Called to interlace the bits in x and y, making a Morton code.
196     function interlace(x, y) {
197       var interlaced_x = x,
198           interlaced_y = y;
199       interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
200       interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
201       interlaced_x = (interlaced_x | (interlaced_x << 2)) & 0x33333333;
202       interlaced_x = (interlaced_x | (interlaced_x << 1)) & 0x55555555;
203       interlaced_y = (interlaced_y | (interlaced_y << 8)) & 0x00ff00ff;
204       interlaced_y = (interlaced_y | (interlaced_y << 4)) & 0x0f0f0f0f;
205       interlaced_y = (interlaced_y | (interlaced_y << 2)) & 0x33333333;
206       interlaced_y = (interlaced_y | (interlaced_y << 1)) & 0x55555555;
207       return (interlaced_x << 1) | interlaced_y;
208     }
209
210     const params = new URLSearchParams();
211     var layers = this.getLayersCode().replace("M", "");
212
213     if (layers) {
214       params.set("layers", layers);
215     }
216
217     if (marker && this.hasLayer(marker)) {
218       params.set("m", "");
219     }
220
221     if (this._object) {
222       params.set(this._object.type, this._object.id);
223     }
224
225     const query = params.toString();
226     if (query) {
227       str += "?" + query;
228     }
229
230     return str;
231   },
232
233   getGeoUri: function (marker) {
234     let latLng = this.getCenter();
235     const zoom = this.getZoom();
236
237     if (marker && this.hasLayer(marker)) {
238       latLng = marker.getLatLng();
239     }
240
241     return `geo:${OSM.cropLocation(latLng, zoom).join(",")}?z=${zoom}`;
242   },
243
244   addObject: function (object, callback) {
245     var objectStyle = {
246       color: "#FF6200",
247       weight: 4,
248       opacity: 1,
249       fillOpacity: 0.5
250     };
251
252     var changesetStyle = {
253       weight: 4,
254       color: "#FF9500",
255       opacity: 1,
256       fillOpacity: 0,
257       interactive: false
258     };
259
260     var haloStyle = {
261       weight: 2.5,
262       radius: 20,
263       fillOpacity: 0.5,
264       color: "#FF6200"
265     };
266
267     this.removeObject();
268
269     if (object.type === "note" || object.type === "changeset") {
270       this._objectLoader = {
271         abort: function () {}
272       };
273
274       this._object = object;
275       this._objectLayer = L.featureGroup().addTo(this);
276
277       if (object.type === "note") {
278         L.circleMarker(object.latLng, haloStyle).addTo(this._objectLayer);
279
280         if (object.icon) {
281           L.marker(object.latLng, {
282             icon: object.icon,
283             opacity: 1,
284             interactive: true
285           }).addTo(this._objectLayer);
286         }
287       } else if (object.type === "changeset") {
288         if (object.bbox) {
289           L.rectangle([
290             [object.bbox.minlat, object.bbox.minlon],
291             [object.bbox.maxlat, object.bbox.maxlon]
292           ], changesetStyle).addTo(this._objectLayer);
293         }
294       }
295
296       if (callback) callback(this._objectLayer.getBounds());
297       this.fire("overlayadd", { layer: this._objectLayer });
298     } else { // element handled by L.OSM.DataLayer
299       var map = this;
300       this._objectLoader = $.ajax({
301         url: OSM.apiUrl(object),
302         dataType: "json",
303         success: function (data) {
304           map._object = object;
305
306           map._objectLayer = new L.OSM.DataLayer(null, {
307             styles: {
308               node: objectStyle,
309               way: objectStyle,
310               area: objectStyle,
311               changeset: changesetStyle
312             }
313           });
314
315           map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
316             if (object.type === "node") {
317               return true;
318             } else if (object.type === "relation") {
319               return Boolean(relationNodes[node.id]);
320             } else {
321               return false;
322             }
323           };
324
325           map._objectLayer.addData(data);
326           map._objectLayer.addTo(map);
327
328           if (callback) callback(map._objectLayer.getBounds());
329           map.fire("overlayadd", { layer: map._objectLayer });
330         }
331       });
332     }
333   },
334
335   removeObject: function () {
336     this._object = null;
337     if (this._objectLoader) this._objectLoader.abort();
338     if (this._objectLayer) this.removeLayer(this._objectLayer);
339     this.fire("overlayremove", { layer: this._objectLayer });
340   },
341
342   getState: function () {
343     return {
344       center: this.getCenter().wrap(),
345       zoom: this.getZoom(),
346       layers: this.getLayersCode()
347     };
348   },
349
350   setState: function (state, options) {
351     if (state.center) this.setView(state.center, state.zoom, options);
352     if (state.layers) this.updateLayers(state.layers);
353   },
354
355   setSidebarOverlaid: function (overlaid) {
356     var sidebarWidth = 350;
357     if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
358       $("#content").addClass("overlay-sidebar");
359       this.invalidateSize({ pan: false });
360       if ($("html").attr("dir") !== "rtl") {
361         this.panBy([-sidebarWidth, 0], { animate: false });
362       }
363     } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
364       if ($("html").attr("dir") !== "rtl") {
365         this.panBy([sidebarWidth, 0], { animate: false });
366       }
367       $("#content").removeClass("overlay-sidebar");
368       this.invalidateSize({ pan: false });
369     }
370     return this;
371   }
372 });
373
374 L.Icon.Default.imagePath = "/images/";
375
376 L.Icon.Default.imageUrls = {
377   "/images/marker-icon.png": OSM.MARKER_ICON,
378   "/images/marker-icon-2x.png": OSM.MARKER_ICON_2X,
379   "/images/marker-shadow.png": OSM.MARKER_SHADOW
380 };
381
382 L.extend(L.Icon.Default.prototype, {
383   _oldGetIconUrl: L.Icon.Default.prototype._getIconUrl,
384
385   _getIconUrl: function (name) {
386     var url = this._oldGetIconUrl(name);
387     return L.Icon.Default.imageUrls[url];
388   }
389 });
390
391 OSM.isDarkMap = function () {
392   var mapTheme = $("body").attr("data-map-theme");
393   if (mapTheme) return mapTheme === "dark";
394   var siteTheme = $("html").attr("data-bs-theme");
395   if (siteTheme) return siteTheme === "dark";
396   return window.matchMedia("(prefers-color-scheme: dark)").matches;
397 };
398
399 OSM.getUserIcon = function (url) {
400   return L.icon({
401     iconUrl: url || OSM.MARKER_RED,
402     iconSize: [25, 41],
403     iconAnchor: [12, 41],
404     popupAnchor: [1, -34],
405     shadowUrl: OSM.MARKER_SHADOW,
406     shadowSize: [41, 41]
407   });
408 };