]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/embed.js.erb
Add OSM.i18n as an alias for I18n
[rails.git] / app / assets / javascripts / embed.js.erb
1 //= depend_on settings.yml
2 //= depend_on settings.local.yml
3 //= depend_on layers.yml
4 //= require leaflet/dist/leaflet-src
5 //= require leaflet.osm
6 //= require i18n
7 //= require i18n/embed
8
9 const OSM = { i18n: I18n };
10
11 if (navigator.languages) {
12   I18n.locale = navigator.languages[0];
13 } else if (navigator.language) {
14   I18n.locale = navigator.language;
15 }
16
17 I18n.default_locale = <%= I18n.default_locale.to_json %>;
18 I18n.fallbacks = true;
19
20 window.onload = function () {
21   const args = Object.fromEntries(new URLSearchParams(location.search));
22
23   const options = {
24     mapnik: {
25 <% if Settings.key?(:tile_cdn_url) %>
26       url: <%= Settings.tile_cdn_url.to_json %>
27 <% end %>
28     }
29   };
30
31   const map = L.map("map");
32   map.attributionControl.setPrefix("");
33   map.removeControl(map.attributionControl);
34
35   const isDarkTheme = args.theme === "dark" || (args.theme !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
36   const layers = <%= MapLayers::embed_definitions("config/layers.yml").to_json %>;
37   const layerId = (args.layer || "").replaceAll(" ", "");
38   const layerConfig = layers[layerId] || layers.mapnik;
39   const layer = (isDarkTheme && layerConfig.leafletOsmDarkId) || layerConfig.leafletOsmId;
40   new L.OSM[layer]({ apikey: layerConfig.apikey, ...options[layerId] }).addTo(map);
41
42   if (args.marker) {
43     L.marker(args.marker.split(","), { icon: L.icon({
44       iconUrl: <%= asset_path('leaflet/dist/images/marker-icon.png').to_json %>,
45       iconSize: new L.Point(25, 41),
46       iconAnchor: new L.Point(12, 41),
47       shadowUrl: <%= asset_path('leaflet/dist/images/marker-shadow.png').to_json %>,
48       shadowSize: new L.Point(41, 41)
49     }) }).addTo(map);
50   }
51
52   const bbox = (args.bbox || "-180,-90,180,90").split(",");
53   map.fitBounds([[bbox[1], bbox[0]], [bbox[3], bbox[2]]]);
54
55   map.addControl(new L.Control.OSMReportAProblem());
56 };
57
58 L.Control.OSMReportAProblem = L.Control.Attribution.extend({
59   options: {
60     position: "bottomright",
61     prefix: `<a href="https://www.openstreetmap.org/fixthemap?lat={x}&lon={y}&zoom={z}" target="_blank">${I18n.t("javascripts.embed.report_problem")}</a>`
62   },
63
64   onAdd: function (map) {
65     const container = L.Control.Attribution.prototype.onAdd.call(this, map);
66
67     map.on("moveend", this._update, this);
68
69     return container;
70   },
71
72   _update: function () {
73     L.Control.Attribution.prototype._update.call(this);
74
75     this._container.innerHTML =
76       this._container.innerHTML
77         .replace("{x}", this._map.getCenter().lat)
78         .replace("{y}", this._map.getCenter().lng)
79         .replace("{z}", this._map.getZoom());
80   }
81 });