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