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