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