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