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}`);
18 const layerConstructor =
19 (OSM.isDarkMap() && L.OSM[leafletOsmDarkId]) ||
20 L.OSM[leafletOsmId] ||
23 const layer = new layerConstructor(layerOptions);
24 layer.on("add", () => {
25 this.fire("baselayerchange", { layer: layer });
30 this.noteLayer = new L.FeatureGroup();
31 this.noteLayer.options = { code: "N" };
33 this.dataLayer = new L.OSM.DataLayer(null);
34 this.dataLayer.options.code = "D";
36 this.gpsLayer = new L.OSM.GPS({
40 this.gpsLayer.on("add", () => {
41 this.fire("overlayadd", { layer: this.gpsLayer });
42 }).on("remove", () => {
43 this.fire("overlayremove", { layer: this.gpsLayer });
46 this.on("baselayerchange", function (event) {
47 if (this.baseLayers.indexOf(event.layer) >= 0) {
48 this.setMaxZoom(event.layer.options.maxZoom);
52 function makeAttribution(credit) {
55 attribution += OSM.i18n.t("javascripts.map.copyright_text", {
56 copyright_link: $("<a>", {
58 text: OSM.i18n.t("javascripts.map.openstreetmap_contributors")
62 attribution += credit.donate ? " ♥ " : ". ";
63 attribution += makeCredit(credit);
66 attribution += $("<a>", {
67 href: "https://wiki.osmfoundation.org/wiki/Terms_of_Use",
68 text: OSM.i18n.t("javascripts.map.website_and_api_terms")
74 function makeCredit(credit) {
76 for (const childId in credit.children) {
77 children[childId] = makeCredit(credit.children[childId]);
79 const text = OSM.i18n.t(`javascripts.map.${credit.id}`, children);
81 const link = $("<a>", {
86 link.addClass("donate-attr");
88 link.attr("target", "_blank");
90 return link.prop("outerHTML");
96 updateLayers: function (layerParam) {
97 const oldBaseLayer = this.getMapBaseLayer();
100 for (const layer of this.baseLayers) {
101 if (!newBaseLayer || layerParam.includes(layer.options.code)) {
102 newBaseLayer = layer;
106 if (newBaseLayer !== oldBaseLayer) {
107 if (oldBaseLayer) this.removeLayer(oldBaseLayer);
108 if (newBaseLayer) this.addLayer(newBaseLayer);
112 getLayersCode: function () {
113 let layerConfig = "";
114 this.eachLayer(function (layer) {
115 if (layer.options && layer.options.code) {
116 layerConfig += layer.options.code;
122 getMapBaseLayerId: function () {
123 const layer = this.getMapBaseLayer();
124 if (layer) return layer.options.layerId;
127 getMapBaseLayer: function () {
128 for (const layer of this.baseLayers) {
129 if (this.hasLayer(layer)) return layer;
133 getUrl: function (marker) {
136 if (marker && this.hasLayer(marker)) {
137 [params.mlat, params.mlon] = OSM.cropLocation(marker.getLatLng(), this.getZoom());
140 let url = location.protocol + "//" + OSM.SERVER_URL + "/";
141 const query = new URLSearchParams(params),
142 hash = OSM.formatHash(this);
144 if (query) url += "?" + query;
145 if (hash) url += hash;
150 getShortUrl: function (marker) {
151 const zoom = this.getZoom(),
152 latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
153 char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
154 x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
155 y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
156 // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
157 // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
158 // and drops the last 4 bits of the full 64 bit Morton code.
159 c1 = interlace(x >>> 17, y >>> 17),
160 c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff);
161 let str = location.protocol + "//" + location.hostname.replace(/^www\.openstreetmap\.org/i, "osm.org") + "/go/";
163 for (let i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
164 const digit = (c1 >> (24 - (6 * i))) & 0x3f;
165 str += char_array.charAt(digit);
167 for (let i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
168 const digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
169 str += char_array.charAt(digit);
171 for (let i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
173 // Called to interlace the bits in x and y, making a Morton code.
174 function interlace(x, y) {
175 let interlaced_x = x,
177 interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
178 interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
179 interlaced_x = (interlaced_x | (interlaced_x << 2)) & 0x33333333;
180 interlaced_x = (interlaced_x | (interlaced_x << 1)) & 0x55555555;
181 interlaced_y = (interlaced_y | (interlaced_y << 8)) & 0x00ff00ff;
182 interlaced_y = (interlaced_y | (interlaced_y << 4)) & 0x0f0f0f0f;
183 interlaced_y = (interlaced_y | (interlaced_y << 2)) & 0x33333333;
184 interlaced_y = (interlaced_y | (interlaced_y << 1)) & 0x55555555;
185 return (interlaced_x << 1) | interlaced_y;
188 const params = new URLSearchParams();
189 const layers = this.getLayersCode().replace("M", "");
192 params.set("layers", layers);
195 if (marker && this.hasLayer(marker)) {
200 params.set(this._object.type, this._object.id);
203 const query = params.toString();
211 getGeoUri: function (marker) {
212 let latLng = this.getCenter();
213 const zoom = this.getZoom();
215 if (marker && this.hasLayer(marker)) {
216 latLng = marker.getLatLng();
219 return `geo:${OSM.cropLocation(latLng, zoom).join(",")}?z=${zoom}`;
222 addObject: function (object, callback) {
223 const objectStyle = {
230 const changesetStyle = {
247 if (object.type === "note" || object.type === "changeset") {
248 this._objectLoader = { abort: () => {} };
250 this._object = object;
251 this._objectLayer = L.featureGroup().addTo(this);
253 if (object.type === "note") {
254 L.circleMarker(object.latLng, haloStyle).addTo(this._objectLayer);
257 L.marker(object.latLng, {
261 }).addTo(this._objectLayer);
263 } else if (object.type === "changeset") {
266 [object.bbox.minlat, object.bbox.minlon],
267 [object.bbox.maxlat, object.bbox.maxlon]
268 ], changesetStyle).addTo(this._objectLayer);
272 if (callback) callback(this._objectLayer.getBounds());
273 this.fire("overlayadd", { layer: this._objectLayer });
274 } else { // element handled by L.OSM.DataLayer
276 this._objectLoader = new AbortController();
277 fetch(OSM.apiUrl(object), {
278 headers: { accept: "application/json" },
279 signal: this._objectLoader.signal
281 .then(async response => {
283 return response.json();
286 const status = response.statusText || response.status;
287 if (response.status !== 400 && response.status !== 509) {
288 throw new Error(status);
291 const text = await response.text();
292 throw new Error(text || status);
294 .then(function (data) {
295 map._object = object;
297 map._objectLayer = new L.OSM.DataLayer(null, {
302 changeset: changesetStyle
306 map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
307 return object.type === "node" ||
308 (object.type === "relation" && Boolean(relationNodes[node.id]));
311 map._objectLayer.addData(data);
312 map._objectLayer.addTo(map);
314 if (callback) callback(map._objectLayer.getBounds());
315 map.fire("overlayadd", { layer: map._objectLayer });
316 $("#browse_status").empty();
318 .catch(function (error) {
319 if (error.name === "AbortError") return;
320 OSM.displayLoadError(error?.message, () => {
321 $("#browse_status").empty();
327 removeObject: function () {
329 if (this._objectLoader) this._objectLoader.abort();
330 if (this._objectLayer) this.removeLayer(this._objectLayer);
331 this.fire("overlayremove", { layer: this._objectLayer });
334 getState: function () {
336 center: this.getCenter().wrap(),
337 zoom: this.getZoom(),
338 layers: this.getLayersCode()
342 setState: function (state, options) {
343 if (state.center) this.setView(state.center, state.zoom, options);
344 if (state.layers) this.updateLayers(state.layers);
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 });
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 });
366 $("#content").removeClass("overlay-sidebar");
367 this.invalidateSize({ pan: false });
373 OSM.isDarkMap = function () {
374 const mapTheme = $("body").attr("data-map-theme");
375 if (mapTheme) return mapTheme === "dark";
376 const siteTheme = $("html").attr("data-bs-theme");
377 if (siteTheme) return siteTheme === "dark";
378 return window.matchMedia("(prefers-color-scheme: dark)").matches;
381 OSM.getMarker = function ({ icon = "dot", color = "var(--marker-red)", ...options }) {
382 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>`;
387 iconAnchor: [12.5, 40],
388 popupAnchor: [1, -34]
393 "closed": OSM.getMarker({ icon: "tick", color: "var(--marker-green)" }),
394 "new": OSM.getMarker({ icon: "plus", color: "var(--marker-blue)" }),
395 "open": OSM.getMarker({ icon: "cross", color: "var(--marker-red)" })