1 //= require download_util
2 L.extend(L.LatLngBounds.prototype, {
4 return (this._northEast.lat - this._southWest.lat) *
5 (this._northEast.lng - this._southWest.lng);
9 L.OSM.Map = L.Map.extend({
10 initialize: function (id, options) {
11 L.Map.prototype.initialize.call(this, id, options);
13 this.baseLayers = OSM.LAYER_DEFINITIONS.map((
14 { credit, nameId, leafletOsmId, leafletOsmDarkId, style, styleDark, ...layerOptions }
16 if (credit) layerOptions.attribution = makeAttribution(credit);
17 if (nameId) layerOptions.name = OSM.i18n.t(`javascripts.map.base.${nameId}`);
20 if (OSM.isDark("map")) {
21 layerConstructor = L.OSM[leafletOsmDarkId] ?? L.OSM[leafletOsmId] ?? L.OSM.TileLayer;
22 layerOptions.url = layerOptions.urlDark ?? layerOptions.url;
24 layerConstructor = L.OSM[leafletOsmId] ?? L.OSM.TileLayer;
27 layerOptions.url = layerOptions.url?.replace("{ratio}", "{r}");
29 const layer = new layerConstructor(layerOptions);
30 layer.on("add", () => {
31 this.fire("baselayerchange", { layer: layer });
33 layer.options.style = (OSM.isDark("map") && styleDark) || style;
37 this.noteLayer = new L.FeatureGroup();
38 this.noteLayer.options = { code: "N" };
40 this.dataLayer = new L.OSM.DataLayer(null);
41 this.dataLayer.options.code = "D";
43 this.gpsLayer = new L.OSM.GPS({
47 this.gpsLayer.on("add", () => {
48 this.fire("overlayadd", { layer: this.gpsLayer });
49 }).on("remove", () => {
50 this.fire("overlayremove", { layer: this.gpsLayer });
53 this.on("baselayerchange", function (event) {
54 if (this.baseLayers.indexOf(event.layer) >= 0) {
55 this.setMaxZoom(event.layer.options.maxZoom);
59 function makeAttribution(credit) {
62 attribution += OSM.i18n.t("javascripts.map.copyright_text", {
63 copyright_link: $("<a>", {
65 text: OSM.i18n.t("javascripts.map.openstreetmap_contributors")
69 attribution += credit.donate ? " ♥️ " : ". ";
70 attribution += makeCredit(credit);
73 attribution += $("<a>", {
74 href: "https://wiki.osmfoundation.org/wiki/Terms_of_Use",
75 text: OSM.i18n.t("javascripts.map.website_and_api_terms")
81 function makeCredit(credit) {
83 for (const childId in credit.children) {
84 children[childId] = makeCredit(credit.children[childId]);
86 const text = OSM.i18n.t(`javascripts.map.${credit.id}`, children);
90 const link = $("<a>", {
95 link.addClass("donate-attr");
97 link.attr("target", "_blank");
99 return link.prop("outerHTML");
103 updateLayers: function (layerParam) {
104 const oldBaseLayer = this.getMapBaseLayer();
107 for (const layer of this.baseLayers) {
108 if (!newBaseLayer || layerParam.includes(layer.options.code)) {
109 newBaseLayer = layer;
113 if (newBaseLayer !== oldBaseLayer) {
114 if (oldBaseLayer) this.removeLayer(oldBaseLayer);
115 if (newBaseLayer) this.addLayer(newBaseLayer);
119 getLayersCode: function () {
120 let layerConfig = "";
121 this.eachLayer(function (layer) {
122 if (layer.options && layer.options.code) {
123 layerConfig += layer.options.code;
129 getMapBaseLayerId: function () {
130 const layer = this.getMapBaseLayer();
131 if (layer) return layer.options.layerId;
134 getMapBaseLayer: function () {
135 for (const layer of this.baseLayers) {
136 if (this.hasLayer(layer)) return layer;
140 getUrl: function (marker) {
141 const search = new URLSearchParams();
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);
152 hash: OSM.formatHash(this)
156 getShortUrl: function (marker) {
157 const zoom = this.getZoom(),
158 latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
159 char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
160 x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
161 y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
162 // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
163 // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
164 // and drops the last 4 bits of the full 64 bit Morton code.
165 c1 = interlace(x >>> 17, y >>> 17),
166 c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff);
167 let pathname = "/go/";
169 for (let i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
170 const digit = (c1 >> (24 - (6 * i))) & 0x3f;
171 pathname += char_array[digit];
173 for (let i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
174 const digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
175 pathname += char_array[digit];
177 for (let i = 0; i < ((zoom + 8) % 3); ++i) pathname += "-";
179 // Called to interlace the bits in x and y, making a Morton code.
180 function interlace(x, y) {
181 let interlaced_x = x,
183 interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
184 interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
185 interlaced_x = (interlaced_x | (interlaced_x << 2)) & 0x33333333;
186 interlaced_x = (interlaced_x | (interlaced_x << 1)) & 0x55555555;
187 interlaced_y = (interlaced_y | (interlaced_y << 8)) & 0x00ff00ff;
188 interlaced_y = (interlaced_y | (interlaced_y << 4)) & 0x0f0f0f0f;
189 interlaced_y = (interlaced_y | (interlaced_y << 2)) & 0x33333333;
190 interlaced_y = (interlaced_y | (interlaced_y << 1)) & 0x55555555;
191 return (interlaced_x << 1) | interlaced_y;
194 const search = new URLSearchParams();
195 const layers = this.getLayersCode().replace("M", "");
198 search.set("layers", layers);
201 if (marker && this.hasLayer(marker)) {
206 search.set(this._object.type, this._object.id);
215 getEmbedUrl: function (marker) {
216 const search = new URLSearchParams({
217 bbox: this.getBounds().toBBoxString(),
218 layer: this.getMapBaseLayerId()
221 if (this.hasLayer(marker)) {
222 const latLng = marker.getLatLng().wrap();
223 search.set("marker", latLng.lat + "," + latLng.lng);
231 getGeoUri: function (marker) {
232 let latLng = this.getCenter();
233 const zoom = this.getZoom();
235 if (marker && this.hasLayer(marker)) {
236 latLng = marker.getLatLng();
239 const { lat, lng } = OSM.cropLocation(latLng, zoom);
240 return `geo:${lat},${lng}?z=${zoom}`;
243 addObject: function (object, callback) {
244 class ElementGoneError extends Error {
245 constructor(message = "Element is gone") {
247 this.name = "ElementGoneError";
251 const objectStyle = {
258 const changesetStyle = {
275 if (object.type === "note" || object.type === "changeset") {
276 this._objectLoader = { abort: () => {} };
278 this._object = object;
279 this._objectLayer = L.featureGroup().addTo(this);
281 if (object.type === "note") {
282 L.circleMarker(object.latLng, haloStyle).addTo(this._objectLayer);
285 L.marker(object.latLng, {
289 }).addTo(this._objectLayer);
291 } else if (object.type === "changeset") {
294 [object.bbox.minlat, object.bbox.minlon],
295 [object.bbox.maxlat, object.bbox.maxlon]
296 ], changesetStyle).addTo(this._objectLayer);
300 if (callback) callback(this._objectLayer.getBounds());
301 this.fire("overlayadd", { layer: this._objectLayer });
302 } else { // element handled by L.OSM.DataLayer
304 this._objectLoader = new AbortController();
305 fetch(OSM.apiUrl(object), {
306 headers: { accept: "application/json", ...OSM.oauth },
307 signal: this._objectLoader.signal
309 .then(async response => {
311 return response.json();
314 if (response.status === 410) {
315 throw new ElementGoneError();
318 const status = `HTTP Error ${response.status} ${response.statusText}`;
319 if (response.status !== 400 && response.status !== 509) {
320 throw new Error(status);
323 const text = await response.text();
324 throw new Error(text || status);
326 .then(function (data) {
327 const visible_data = {
329 elements: data.elements?.filter(el => el.visible !== false) ?? []
332 map._object = object;
334 map._objectLayer = new L.OSM.DataLayer(null, {
339 changeset: changesetStyle
343 map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
344 return object.type === "node" ||
345 (object.type === "relation" && Boolean(relationNodes[node.id]));
348 map._objectLayer.addData(visible_data);
349 map._objectLayer.addTo(map);
351 if (callback) callback(map._objectLayer.getBounds());
352 map.fire("overlayadd", { layer: map._objectLayer });
353 $("#browse_status").empty();
355 .catch(function (error) {
356 if (error.name === "AbortError") return;
357 if (error instanceof ElementGoneError) {
358 $("#browse_status").empty();
361 OSM.displayLoadError(error?.message, () => {
362 $("#browse_status").empty();
368 removeObject: function () {
370 if (this._objectLoader) this._objectLoader.abort();
371 if (this._objectLayer) this.removeLayer(this._objectLayer);
372 this.fire("overlayremove", { layer: this._objectLayer });
375 getState: function () {
377 center: this.getCenter().wrap(),
378 zoom: this.getZoom(),
379 layers: this.getLayersCode()
383 setState: function (state, options) {
384 if (state.center) this.setView(state.center, state.zoom, options);
385 if (state.layers) this.updateLayers(state.layers);
388 setSidebarOverlaid: function (overlaid) {
389 const mediumDeviceWidth = window.getComputedStyle(document.documentElement).getPropertyValue("--bs-breakpoint-md");
390 const isMediumDevice = window.matchMedia(`(max-width: ${mediumDeviceWidth})`).matches;
391 const sidebarWidth = $("#sidebar").width();
392 const sidebarHeight = $("#sidebar").height();
393 if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
394 $("#content").addClass("overlay-sidebar");
395 this.invalidateSize({ pan: false });
396 if (isMediumDevice) {
397 this.panBy([0, -sidebarHeight], { animate: false });
398 } else if ($("html").attr("dir") !== "rtl") {
399 this.panBy([-sidebarWidth, 0], { animate: false });
401 } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
402 if (isMediumDevice) {
403 this.panBy([0, $("#map").height() / 2], { animate: false });
404 } else if ($("html").attr("dir") !== "rtl") {
405 this.panBy([sidebarWidth, 0], { animate: false });
407 $("#content").removeClass("overlay-sidebar");
408 this.invalidateSize({ pan: false });
414 OSM.getMarker = function ({ icon = "dot", color = "var(--marker-red)", ...options }) {
415 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>`;
420 iconAnchor: [12.5, 40],
421 popupAnchor: [1, -34]
426 "closed": OSM.getMarker({ icon: "tick", color: "var(--marker-green)" }),
427 "new": OSM.getMarker({ icon: "plus", color: "var(--marker-blue)" }),
428 "open": OSM.getMarker({ icon: "cross", color: "var(--marker-red)" })