]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/maplibre/map.js
Merge pull request #7302 from tomhughes/terms-locale
[rails.git] / app / assets / javascripts / maplibre / map.js
1 //= require maplibre/controls
2 //= require maplibre/marker
3 //= require maplibre/popup
4
5 maplibregl.Map.prototype._getUIString = function (key) {
6   const snakeCaseKey = key.replaceAll(/(?<=\w)[A-Z]/g, "_$&").toLowerCase();
7   return OSM.i18n.t(`javascripts.map.${snakeCaseKey}`);
8 };
9
10 OSM.MapLibre.showWebGLError = function (container) {
11   const containerElement =
12     typeof container === "string" ? document.getElementById(container) : container;
13
14   if (containerElement) {
15     fetch("/panes/webgl_error")
16       .then(response => response.text())
17       .then(html => containerElement.innerHTML = html);
18   }
19 };
20
21 OSM.MapLibre.Map = class extends maplibregl.Map {
22   constructor({ allowRotation, ...options } = {}) {
23     const rotationOptions = {};
24     if (allowRotation === false) {
25       Object.assign(rotationOptions, {
26         rollEnabled: false,
27         dragRotate: false,
28         pitchWithRotate: false,
29         bearingSnap: 180
30       });
31     }
32
33     let map;
34     try {
35       map = super({
36         // Style validation only affects debug output.
37         // Style errors are usually reported to authors, who should validate the style in CI for better error messages.
38         validateStyle: false,
39         ...rotationOptions,
40         ...options
41       });
42     } catch (error) {
43       const structuredError = JSON.parse(error.message);
44       if (structuredError.type === "webglcontextcreationerror") {
45         OSM.MapLibre.showWebGLError(options.container);
46       }
47       // the constructor panicked => we need to re-throw
48       throw error;
49     }
50     if (allowRotation === false) {
51       map.touchZoomRotate.disableRotation();
52       map.keyboard.disableRotation();
53     }
54     return map;
55   }
56
57   getZoom() {
58     // Convert MapLibre's 512px based zoom to OSM's 256px based zoom.
59     return super.getZoom() + 1;
60   }
61
62   setZoom(zoom, ...args) {
63     return super.setZoom(zoom - 1, ...args);
64   }
65
66   zoomTo(zoom, ...args) {
67     return super.zoomTo(zoom - 1, ...args);
68   }
69 };
70
71 OSM.MapLibre.SecondaryMap = class extends OSM.MapLibre.Map {
72   constructor(options = {}) {
73     const defaultHomeZoom = 11;
74     super({
75       container: "map",
76       style: OSM.LAYER_DEFINITIONS[0].style,
77       attributionControl: false,
78       allowRotation: false,
79       maxPitch: 0,
80       center: OSM.home ? [OSM.home.lon, OSM.home.lat] : [0, 0],
81       zoom: OSM.home ? defaultHomeZoom : 0,
82       zoomSnap: 1.0,
83       ...options
84     });
85   }
86 };