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