]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/leaflet.share.js
Refactor map download functions
[rails.git] / app / assets / javascripts / leaflet.share.js
1 //= require download_util
2
3 L.OSM.share = function (options) {
4   const control = L.OSM.sidebarPane(options, "share", "javascripts.share.title", "javascripts.share.title"),
5         marker = L.marker([0, 0], { draggable: true, icon: OSM.getMarker({ color: "var(--marker-blue)" }) }),
6         locationFilter = new L.LocationFilter({
7           enableButton: false,
8           adjustButton: false
9         });
10
11   function init(map, $ui) {
12     // Link / Embed
13
14     $ui.find("#link_marker").on("change", toggleMarker);
15
16     $ui.find(".btn-group .btn")
17       .on("shown.bs.tab", () => {
18         $ui.find(".tab-pane.active [id]")
19           .trigger("select");
20       });
21
22     $ui.find(".share-tab [id]").on("click", select);
23
24     // Image
25
26     $ui.find("#mapnik_scale").on("change", update);
27
28     $ui.find("#image_filter").bind("change", toggleFilter);
29
30     const csrfInput = $ui.find("#csrf_export")[0];
31     [[csrfInput.name, csrfInput.value]] = Object.entries(OSM.csrf);
32
33
34     document.getElementById("export-image")
35       .addEventListener("turbo:submit-end",
36                         OSM.getTurboBlobHandler(OSM.i18n.t("javascripts.share.filename")));
37
38     document.getElementById("export-image").addEventListener("turbo:before-fetch-response", function (event) {
39       const response = event.detail.fetchResponse.response;
40       const contentType = response.headers.get("content-type");
41
42       if (!response.ok && contentType?.includes("text/html")) {
43         // Prevent Turbo from replacing the current page with an error HTML response
44         // from the image export endpoint
45         event.preventDefault();
46         event.stopPropagation();
47       }
48     });
49
50     locationFilter
51       .on("change", update)
52       .addTo(map);
53
54     marker.on("dragend", movedMarker);
55     map.on("move", movedMap);
56     map.on("moveend baselayerchange overlayadd overlayremove", update);
57
58     $ui
59       .on("show", shown)
60       .on("hide", hidden);
61
62     update();
63
64     function shown() {
65       $("#mapnik_scale").val(getScale());
66       update();
67     }
68
69     function hidden() {
70       map.removeLayer(marker);
71       map.options.scrollWheelZoom = map.options.doubleClickZoom = true;
72       locationFilter.disable();
73       update();
74     }
75
76     function toggleMarker() {
77       if ($(this).is(":checked")) {
78         marker.setLatLng(map.getCenter());
79         map.addLayer(marker);
80         map.options.scrollWheelZoom = map.options.doubleClickZoom = "center";
81       } else {
82         map.removeLayer(marker);
83         map.options.scrollWheelZoom = map.options.doubleClickZoom = true;
84       }
85       update();
86     }
87
88     function toggleFilter() {
89       if ($(this).is(":checked")) {
90         locationFilter.setBounds(map.getBounds().pad(-0.2));
91         locationFilter.enable();
92       } else {
93         locationFilter.disable();
94       }
95       update();
96     }
97
98     function movedMap() {
99       marker.setLatLng(map.getCenter());
100       update();
101     }
102
103     function movedMarker() {
104       if (map.hasLayer(marker)) {
105         map.off("move", movedMap);
106         map.on("moveend", updateOnce);
107         map.panTo(marker.getLatLng());
108       }
109     }
110
111     function updateOnce() {
112       map.off("moveend", updateOnce);
113       map.on("move", movedMap);
114       update();
115     }
116
117     function escapeHTML(string) {
118       const htmlEscapes = {
119         "&": "&",
120         "<": "&lt;",
121         ">": "&gt;",
122         "\"": "&quot;",
123         "'": "&#x27;"
124       };
125       return string === null ? "" : String(string).replace(/[&<>"']/g, function (match) {
126         return htmlEscapes[match];
127       });
128     }
129
130     function update() {
131       const layer = map.getMapBaseLayer();
132       const canEmbed = Boolean(layer && layer.options.canEmbed);
133       let bounds = map.getBounds();
134
135       $("#link_marker")
136         .prop("checked", map.hasLayer(marker));
137
138       $("#image_filter")
139         .prop("checked", locationFilter.isEnabled());
140
141       // Link / Embed
142
143       $("#short_input").val(map.getShortUrl(marker));
144       $("#long_input").val(map.getUrl(marker));
145       $("#short_link").attr("href", map.getShortUrl(marker));
146       $("#long_link").attr("href", map.getUrl(marker));
147
148       const params = new URLSearchParams({
149         bbox: bounds.toBBoxString(),
150         layer: map.getMapBaseLayerId()
151       });
152
153       if (map.hasLayer(marker)) {
154         const latLng = marker.getLatLng().wrap();
155         params.set("marker", latLng.lat + "," + latLng.lng);
156       }
157
158       if (!canEmbed && $("#nav-embed").hasClass("active")) {
159         bootstrap.Tab.getOrCreateInstance($("#long_link")).show();
160       }
161       $("#embed_link")
162         .toggleClass("disabled", !canEmbed)
163         .parent()
164         .tooltip(canEmbed ? "disable" : "enable");
165
166       $("#embed_html").val(
167         "<iframe width=\"425\" height=\"350\" src=\"" +
168           escapeHTML(OSM.SERVER_PROTOCOL + "://" + OSM.SERVER_URL + "/export/embed.html?" + params) +
169           "\" style=\"border: 1px solid black\"></iframe><br/>" +
170           "<small><a href=\"" + escapeHTML(map.getUrl(marker)) + "\">" +
171           escapeHTML(OSM.i18n.t("javascripts.share.view_larger_map")) + "</a></small>");
172
173       // Geo URI
174
175       $("#geo_uri")
176         .attr("href", map.getGeoUri(marker))
177         .text(map.getGeoUri(marker));
178
179       // Image
180
181       if (locationFilter.isEnabled()) {
182         bounds = locationFilter.getBounds();
183       }
184
185       let scale = $("#mapnik_scale").val();
186       const size = L.bounds(L.CRS.EPSG3857.project(bounds.getSouthWest()),
187                             L.CRS.EPSG3857.project(bounds.getNorthEast())).getSize(),
188             maxScale = Math.floor(Math.sqrt(size.x * size.y / 0.3136));
189
190       $("#mapnik_minlon").val(bounds.getWest());
191       $("#mapnik_minlat").val(bounds.getSouth());
192       $("#mapnik_maxlon").val(bounds.getEast());
193       $("#mapnik_maxlat").val(bounds.getNorth());
194
195       if (scale < maxScale) {
196         scale = roundScale(maxScale);
197         $("#mapnik_scale").val(scale);
198       }
199
200       const mapWidth = Math.round(size.x / scale / 0.00028);
201       const mapHeight = Math.round(size.y / scale / 0.00028);
202       $("#mapnik_image_width").text(mapWidth);
203       $("#mapnik_image_height").text(mapHeight);
204
205       const canDownloadImage = Boolean(layer && layer.options.canDownloadImage);
206
207       $("#mapnik_image_layer").text(canDownloadImage ? layer.options.name : "");
208       $("#map_format").val(canDownloadImage ? layer.options.layerId : "");
209
210       $("#map_zoom").val(map.getZoom());
211       $("#mapnik_lon").val(map.getCenter().lng);
212       $("#mapnik_lat").val(map.getCenter().lat);
213       $("#map_width").val(mapWidth);
214       $("#map_height").val(mapHeight);
215
216       $("#export-image").toggle(canDownloadImage);
217       $("#export-warning").toggle(!canDownloadImage);
218       $("#mapnik_scale_row").toggle(canDownloadImage && layer.options.layerId === "mapnik");
219     }
220
221     function select() {
222       $(this).trigger("select");
223     }
224
225     function getScale() {
226       const bounds = map.getBounds(),
227             centerLat = bounds.getCenter().lat,
228             halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
229             meters = halfWorldMeters * (bounds.getEast() - bounds.getWest()) / 180,
230             pixelsPerMeter = map.getSize().x / meters,
231             metersPerPixel = 1 / (92 * 39.3701);
232       return Math.round(1 / (pixelsPerMeter * metersPerPixel));
233     }
234
235     function roundScale(scale) {
236       const precision = 5 * Math.pow(10, Math.floor(Math.LOG10E * Math.log(scale)) - 2);
237       return precision * Math.ceil(scale / precision);
238     }
239   }
240
241   control.onAddPane = function (map, button, $ui) {
242     $("#content").addClass("overlay-right-sidebar");
243
244     control.onContentLoaded = () => init(map, $ui);
245     $ui.one("show", control.loadContent);
246   };
247
248   return control;
249 };