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, ...layerOptions }
16 if (credit) layerOptions.attribution = makeAttribution(credit);
17 if (nameId) layerOptions.name = OSM.i18n.t(`javascripts.map.base.${nameId}`);
19 if (OSM.isDarkMap() && L.OSM[leafletOsmDarkId]) {
20 layerOptions.leafletOsmId = leafletOsmDarkId;
21 } else if (L.OSM[leafletOsmId]) {
22 layerOptions.leafletOsmId = leafletOsmId;
24 layerOptions.leafletOsmId = "TileLayer";
27 const layerConstructor = L.OSM[layerOptions.leafletOsmId];
29 const layer = new layerConstructor(layerOptions);
30 layer.on("add", () => {
31 this.fire("baselayerchange", { layer: layer });
36 this.noteLayer = new L.FeatureGroup();
37 this.noteLayer.options = { code: "N" };
39 this.dataLayer = new L.OSM.DataLayer(null);
40 this.dataLayer.options.code = "D";
42 this.gpsLayer = new L.OSM.GPS({
46 this.gpsLayer.on("add", () => {
47 this.fire("overlayadd", { layer: this.gpsLayer });
48 }).on("remove", () => {
49 this.fire("overlayremove", { layer: this.gpsLayer });
52 this.on("baselayerchange", function (event) {
53 if (this.baseLayers.indexOf(event.layer) >= 0) {
54 this.setMaxZoom(event.layer.options.maxZoom);
58 function makeAttribution(credit) {
61 attribution += OSM.i18n.t("javascripts.map.copyright_text", {
62 copyright_link: $("<a>", {
64 text: OSM.i18n.t("javascripts.map.openstreetmap_contributors")
68 attribution += credit.donate ? " ♥️ " : ". ";
69 attribution += makeCredit(credit);
72 attribution += $("<a>", {
73 href: "https://wiki.osmfoundation.org/wiki/Terms_of_Use",
74 text: OSM.i18n.t("javascripts.map.website_and_api_terms")
80 function makeCredit(credit) {
82 for (const childId in credit.children) {
83 children[childId] = makeCredit(credit.children[childId]);
85 const text = OSM.i18n.t(`javascripts.map.${credit.id}`, children);
87 const link = $("<a>", {
92 link.addClass("donate-attr");
94 link.attr("target", "_blank");
96 return link.prop("outerHTML");
102 updateLayers: function (layerParam) {
103 const oldBaseLayer = this.getMapBaseLayer();
106 for (const layer of this.baseLayers) {
107 if (!newBaseLayer || layerParam.includes(layer.options.code)) {
108 newBaseLayer = layer;
112 if (newBaseLayer !== oldBaseLayer) {
113 if (oldBaseLayer) this.removeLayer(oldBaseLayer);
114 if (newBaseLayer) this.addLayer(newBaseLayer);
118 getLayersCode: function () {
119 let layerConfig = "";
120 this.eachLayer(function (layer) {
121 if (layer.options && layer.options.code) {
122 layerConfig += layer.options.code;
128 getMapBaseLayerId: function () {
129 const layer = this.getMapBaseLayer();
130 if (layer) return layer.options.layerId;
133 getMapBaseLayer: function () {
134 for (const layer of this.baseLayers) {
135 if (this.hasLayer(layer)) return layer;
139 getUrl: function (marker) {
142 if (marker && this.hasLayer(marker)) {
143 [params.mlat, params.mlon] = OSM.cropLocation(marker.getLatLng(), this.getZoom());
146 let url = location.protocol + "//" + OSM.SERVER_URL + "/";
147 const query = new URLSearchParams(params),
148 hash = OSM.formatHash(this);
150 if (query) url += "?" + query;
151 if (hash) url += hash;
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 str = location.protocol + "//" + location.hostname.replace(/^www\.openstreetmap\.org/i, "osm.org") + "/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 str += char_array.charAt(digit);
173 for (let i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
174 const digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
175 str += char_array.charAt(digit);
177 for (let i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
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 params = new URLSearchParams();
195 const layers = this.getLayersCode().replace("M", "");
198 params.set("layers", layers);
201 if (marker && this.hasLayer(marker)) {
206 params.set(this._object.type, this._object.id);
209 const query = params.toString();
217 getGeoUri: function (marker) {
218 let latLng = this.getCenter();
219 const zoom = this.getZoom();
221 if (marker && this.hasLayer(marker)) {
222 latLng = marker.getLatLng();
225 return `geo:${OSM.cropLocation(latLng, zoom).join(",")}?z=${zoom}`;
228 addObject: function (object, callback) {
229 class ElementGoneError extends Error {
230 constructor(message = "Element is gone") {
232 this.name = "ElementGoneError";
236 const objectStyle = {
243 const changesetStyle = {
260 if (object.type === "note" || object.type === "changeset") {
261 this._objectLoader = { abort: () => {} };
263 this._object = object;
264 this._objectLayer = L.featureGroup().addTo(this);
266 if (object.type === "note") {
267 L.circleMarker(object.latLng, haloStyle).addTo(this._objectLayer);
270 L.marker(object.latLng, {
274 }).addTo(this._objectLayer);
276 } else if (object.type === "changeset") {
279 [object.bbox.minlat, object.bbox.minlon],
280 [object.bbox.maxlat, object.bbox.maxlon]
281 ], changesetStyle).addTo(this._objectLayer);
285 if (callback) callback(this._objectLayer.getBounds());
286 this.fire("overlayadd", { layer: this._objectLayer });
287 } else { // element handled by L.OSM.DataLayer
289 this._objectLoader = new AbortController();
290 fetch(OSM.apiUrl(object), {
291 headers: { accept: "application/json", ...OSM.oauth },
292 signal: this._objectLoader.signal
294 .then(async response => {
296 return response.json();
299 if (response.status === 410) {
300 throw new ElementGoneError();
303 const status = response.statusText || response.status;
304 if (response.status !== 400 && response.status !== 509) {
305 throw new Error(status);
308 const text = await response.text();
309 throw new Error(text || status);
311 .then(function (data) {
312 const visible_data = {
314 elements: data.elements?.filter(el => el.visible !== false) ?? []
317 map._object = object;
319 map._objectLayer = new L.OSM.DataLayer(null, {
324 changeset: changesetStyle
328 map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
329 return object.type === "node" ||
330 (object.type === "relation" && Boolean(relationNodes[node.id]));
333 map._objectLayer.addData(visible_data);
334 map._objectLayer.addTo(map);
336 if (callback) callback(map._objectLayer.getBounds());
337 map.fire("overlayadd", { layer: map._objectLayer });
338 $("#browse_status").empty();
340 .catch(function (error) {
341 if (error.name === "AbortError") return;
342 if (error instanceof ElementGoneError) {
343 $("#browse_status").empty();
346 OSM.displayLoadError(error?.message, () => {
347 $("#browse_status").empty();
353 removeObject: function () {
355 if (this._objectLoader) this._objectLoader.abort();
356 if (this._objectLayer) this.removeLayer(this._objectLayer);
357 this.fire("overlayremove", { layer: this._objectLayer });
360 getState: function () {
362 center: this.getCenter().wrap(),
363 zoom: this.getZoom(),
364 layers: this.getLayersCode()
368 setState: function (state, options) {
369 if (state.center) this.setView(state.center, state.zoom, options);
370 if (state.layers) this.updateLayers(state.layers);
373 setSidebarOverlaid: function (overlaid) {
374 const mediumDeviceWidth = window.getComputedStyle(document.documentElement).getPropertyValue("--bs-breakpoint-md");
375 const isMediumDevice = window.matchMedia(`(max-width: ${mediumDeviceWidth})`).matches;
376 const sidebarWidth = $("#sidebar").width();
377 const sidebarHeight = $("#sidebar").height();
378 if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
379 $("#content").addClass("overlay-sidebar");
380 this.invalidateSize({ pan: false });
381 if (isMediumDevice) {
382 this.panBy([0, -sidebarHeight], { animate: false });
383 } else if ($("html").attr("dir") !== "rtl") {
384 this.panBy([-sidebarWidth, 0], { animate: false });
386 } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
387 if (isMediumDevice) {
388 this.panBy([0, $("#map").height() / 2], { animate: false });
389 } else if ($("html").attr("dir") !== "rtl") {
390 this.panBy([sidebarWidth, 0], { animate: false });
392 $("#content").removeClass("overlay-sidebar");
393 this.invalidateSize({ pan: false });
399 OSM.isDarkMap = function () {
400 const mapTheme = $("body").attr("data-map-theme");
401 if (mapTheme) return mapTheme === "dark";
402 return window.matchMedia("(prefers-color-scheme: dark)").matches;
405 OSM.getMarker = function ({ icon = "dot", color = "var(--marker-red)", ...options }) {
406 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>`;
411 iconAnchor: [12.5, 40],
412 popupAnchor: [1, -34]
417 "closed": OSM.getMarker({ icon: "tick", color: "var(--marker-green)" }),
418 "new": OSM.getMarker({ icon: "plus", color: "var(--marker-blue)" }),
419 "open": OSM.getMarker({ icon: "cross", color: "var(--marker-red)" })