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