]> git.openstreetmap.org Git - rails.git/blobdiff - app/assets/javascripts/leaflet.map.js
Associate search input with route destination instead of departure
[rails.git] / app / assets / javascripts / leaflet.map.js
index e0c2ee60b47fb0ddd5251ac520b3c8e234f8ebca..34c0bd449174a962e61124d3bd14f575999112ce 100644 (file)
@@ -1,5 +1,3 @@
-//= require qs/dist/qs
-
 L.extend(L.LatLngBounds.prototype, {
   getSize: function () {
     return (this._northEast.lat - this._southWest.lat) *
@@ -32,12 +30,17 @@ L.OSM.Map = L.Map.extend({
           layerOptions.apikey = OSM[value];
         } else if (property === "leafletOsmId") {
           layerConstructor = L.OSM[value];
+        } else if (property === "leafletOsmDarkId" && OSM.isDarkMap() && L.OSM[value]) {
+          layerConstructor = L.OSM[value];
         } else {
           layerOptions[property] = value;
         }
       }
 
       const layer = new layerConstructor(layerOptions);
+      layer.on("add", () => {
+        this.fire("baselayerchange", { layer: layer });
+      });
       this.baseLayers.push(layer);
     }
 
@@ -51,8 +54,14 @@ L.OSM.Map = L.Map.extend({
       pane: "overlayPane",
       code: "G"
     });
+    this.gpsLayer.on("add", () => {
+      this.fire("overlayadd", { layer: this.gpsLayer });
+    }).on("remove", () => {
+      this.fire("overlayremove", { layer: this.gpsLayer });
+    });
 
-    this.on("layeradd", function (event) {
+
+    this.on("baselayerchange", function (event) {
       if (this.baseLayers.indexOf(event.layer) >= 0) {
         this.setMaxZoom(event.layer.options.maxZoom);
       }
@@ -97,30 +106,29 @@ L.OSM.Map = L.Map.extend({
           link.attr("target", "_blank");
         }
         return link.prop("outerHTML");
-      } else {
-        return text;
       }
+      return text;
     }
   },
 
   updateLayers: function (layerParam) {
-    var layers = layerParam || "M",
-        layersAdded = "";
-
-    for (var i = this.baseLayers.length - 1; i >= 0; i--) {
-      if (layers.indexOf(this.baseLayers[i].options.code) >= 0) {
-        this.addLayer(this.baseLayers[i]);
-        layersAdded = layersAdded + this.baseLayers[i].options.code;
-      } else if (i === 0 && layersAdded === "") {
-        this.addLayer(this.baseLayers[i]);
-      } else {
-        this.removeLayer(this.baseLayers[i]);
+    const oldBaseLayer = this.getMapBaseLayer();
+    let newBaseLayer;
+
+    for (const layer of this.baseLayers) {
+      if (!newBaseLayer || layerParam.includes(layer.options.code)) {
+        newBaseLayer = layer;
       }
     }
+
+    if (newBaseLayer !== oldBaseLayer) {
+      if (oldBaseLayer) this.removeLayer(oldBaseLayer);
+      if (newBaseLayer) this.addLayer(newBaseLayer);
+    }
   },
 
   getLayersCode: function () {
-    var layerConfig = "";
+    let layerConfig = "";
     this.eachLayer(function (layer) {
       if (layer.options && layer.options.code) {
         layerConfig += layer.options.code;
@@ -141,18 +149,15 @@ L.OSM.Map = L.Map.extend({
   },
 
   getUrl: function (marker) {
-    var precision = OSM.zoomPrecision(this.getZoom()),
-        params = {};
+    const params = {};
 
     if (marker && this.hasLayer(marker)) {
-      var latLng = marker.getLatLng().wrap();
-      params.mlat = latLng.lat.toFixed(precision);
-      params.mlon = latLng.lng.toFixed(precision);
+      [params.mlat, params.mlon] = OSM.cropLocation(marker.getLatLng(), this.getZoom());
     }
 
-    var url = window.location.protocol + "//" + OSM.SERVER_URL + "/",
-        query = Qs.stringify(params),
-        hash = OSM.formatHash(this);
+    let url = window.location.protocol + "//" + OSM.SERVER_URL + "/";
+    const query = new URLSearchParams(params),
+          hash = OSM.formatHash(this);
 
     if (query) url += "?" + query;
     if (hash) url += hash;
@@ -161,34 +166,31 @@ L.OSM.Map = L.Map.extend({
   },
 
   getShortUrl: function (marker) {
-    var zoom = this.getZoom(),
-        latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
-        str = window.location.hostname.match(/^www\.openstreetmap\.org/i) ?
-          window.location.protocol + "//osm.org/go/" :
-          window.location.protocol + "//" + window.location.hostname + "/go/",
-        char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
-        x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
-        y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
-        // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
-        // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
-        // and drops the last 4 bits of the full 64 bit Morton code.
-        c1 = interlace(x >>> 17, y >>> 17), c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff),
-        digit,
-        i;
-
-    for (i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
-      digit = (c1 >> (24 - (6 * i))) & 0x3f;
+    const zoom = this.getZoom(),
+          latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
+          char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
+          x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
+          y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
+          // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
+          // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
+          // and drops the last 4 bits of the full 64 bit Morton code.
+          c1 = interlace(x >>> 17, y >>> 17),
+          c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff);
+    let str = window.location.protocol + "//" + window.location.hostname.replace(/^www\.openstreetmap\.org/i, "osm.org") + "/go/";
+
+    for (let i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
+      const digit = (c1 >> (24 - (6 * i))) & 0x3f;
       str += char_array.charAt(digit);
     }
-    for (i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
-      digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
+    for (let i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
+      const digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
       str += char_array.charAt(digit);
     }
-    for (i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
+    for (let i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
 
     // Called to interlace the bits in x and y, making a Morton code.
     function interlace(x, y) {
-      var interlaced_x = x,
+      let interlaced_x = x,
           interlaced_y = y;
       interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
       interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
@@ -201,22 +203,22 @@ L.OSM.Map = L.Map.extend({
       return (interlaced_x << 1) | interlaced_y;
     }
 
-    var params = {};
-    var layers = this.getLayersCode().replace("M", "");
+    const params = new URLSearchParams();
+    const layers = this.getLayersCode().replace("M", "");
 
     if (layers) {
-      params.layers = layers;
+      params.set("layers", layers);
     }
 
     if (marker && this.hasLayer(marker)) {
-      params.m = "";
+      params.set("m", "");
     }
 
     if (this._object) {
-      params[this._object.type] = this._object.id;
+      params.set(this._object.type, this._object.id);
     }
 
-    var query = Qs.stringify(params);
+    const query = params.toString();
     if (query) {
       str += "?" + query;
     }
@@ -225,32 +227,25 @@ L.OSM.Map = L.Map.extend({
   },
 
   getGeoUri: function (marker) {
-    var precision = OSM.zoomPrecision(this.getZoom()),
-        latLng,
-        params = {};
+    let latLng = this.getCenter();
+    const zoom = this.getZoom();
 
     if (marker && this.hasLayer(marker)) {
-      latLng = marker.getLatLng().wrap();
-    } else {
-      latLng = this.getCenter();
+      latLng = marker.getLatLng();
     }
 
-    params.lat = latLng.lat.toFixed(precision);
-    params.lon = latLng.lng.toFixed(precision);
-    params.zoom = this.getZoom();
-
-    return "geo:" + params.lat + "," + params.lon + "?z=" + params.zoom;
+    return `geo:${OSM.cropLocation(latLng, zoom).join(",")}?z=${zoom}`;
   },
 
   addObject: function (object, callback) {
-    var objectStyle = {
+    const objectStyle = {
       color: "#FF6200",
       weight: 4,
       opacity: 1,
       fillOpacity: 0.5
     };
 
-    var changesetStyle = {
+    const changesetStyle = {
       weight: 4,
       color: "#FF9500",
       opacity: 1,
@@ -258,7 +253,7 @@ L.OSM.Map = L.Map.extend({
       interactive: false
     };
 
-    var haloStyle = {
+    const haloStyle = {
       weight: 2.5,
       radius: 20,
       fillOpacity: 0.5,
@@ -268,9 +263,7 @@ L.OSM.Map = L.Map.extend({
     this.removeObject();
 
     if (object.type === "note" || object.type === "changeset") {
-      this._objectLoader = {
-        abort: function () {}
-      };
+      this._objectLoader = { abort: () => {} };
 
       this._object = object;
       this._objectLayer = L.featureGroup().addTo(this);
@@ -295,12 +288,16 @@ L.OSM.Map = L.Map.extend({
       }
 
       if (callback) callback(this._objectLayer.getBounds());
+      this.fire("overlayadd", { layer: this._objectLayer });
     } else { // element handled by L.OSM.DataLayer
-      var map = this;
-      this._objectLoader = $.ajax({
-        url: OSM.apiUrl(object),
-        dataType: "xml",
-        success: function (xml) {
+      const map = this;
+      this._objectLoader = new AbortController();
+      fetch(OSM.apiUrl(object), {
+        headers: { accept: "application/json" },
+        signal: this._objectLoader.signal
+      })
+        .then(response => response.json())
+        .then(function (data) {
           map._object = object;
 
           map._objectLayer = new L.OSM.DataLayer(null, {
@@ -313,21 +310,17 @@ L.OSM.Map = L.Map.extend({
           });
 
           map._objectLayer.interestingNode = function (node, wayNodes, relationNodes) {
-            if (object.type === "node") {
-              return true;
-            } else if (object.type === "relation") {
-              return Boolean(relationNodes[node.id]);
-            } else {
-              return false;
-            }
+            return object.type === "node" ||
+                   (object.type === "relation" && Boolean(relationNodes[node.id]));
           };
 
-          map._objectLayer.addData(xml);
+          map._objectLayer.addData(data);
           map._objectLayer.addTo(map);
 
           if (callback) callback(map._objectLayer.getBounds());
-        }
-      });
+          map.fire("overlayadd", { layer: map._objectLayer });
+        })
+        .catch(() => {});
     }
   },
 
@@ -335,6 +328,7 @@ L.OSM.Map = L.Map.extend({
     this._object = null;
     if (this._objectLoader) this._objectLoader.abort();
     if (this._objectLayer) this.removeLayer(this._objectLayer);
+    this.fire("overlayremove", { layer: this._objectLayer });
   },
 
   getState: function () {
@@ -351,15 +345,22 @@ L.OSM.Map = L.Map.extend({
   },
 
   setSidebarOverlaid: function (overlaid) {
-    var sidebarWidth = 350;
+    const mediumDeviceWidth = window.getComputedStyle(document.documentElement).getPropertyValue("--bs-breakpoint-md");
+    const isMediumDevice = window.matchMedia(`(max-width: ${mediumDeviceWidth})`).matches;
+    const sidebarWidth = $("#sidebar").width();
+    const sidebarHeight = $("#sidebar").height();
     if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
       $("#content").addClass("overlay-sidebar");
       this.invalidateSize({ pan: false });
-      if ($("html").attr("dir") !== "rtl") {
+      if (isMediumDevice) {
+        this.panBy([0, -sidebarHeight], { animate: false });
+      } else if ($("html").attr("dir") !== "rtl") {
         this.panBy([-sidebarWidth, 0], { animate: false });
       }
     } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
-      if ($("html").attr("dir") !== "rtl") {
+      if (isMediumDevice) {
+        this.panBy([0, $("#map").height() / 2], { animate: false });
+      } else if ($("html").attr("dir") !== "rtl") {
         this.panBy([sidebarWidth, 0], { animate: false });
       }
       $("#content").removeClass("overlay-sidebar");
@@ -381,11 +382,19 @@ L.extend(L.Icon.Default.prototype, {
   _oldGetIconUrl: L.Icon.Default.prototype._getIconUrl,
 
   _getIconUrl: function (name) {
-    var url = this._oldGetIconUrl(name);
+    const url = this._oldGetIconUrl(name);
     return L.Icon.Default.imageUrls[url];
   }
 });
 
+OSM.isDarkMap = function () {
+  const mapTheme = $("body").attr("data-map-theme");
+  if (mapTheme) return mapTheme === "dark";
+  const siteTheme = $("html").attr("data-bs-theme");
+  if (siteTheme) return siteTheme === "dark";
+  return window.matchMedia("(prefers-color-scheme: dark)").matches;
+};
+
 OSM.getUserIcon = function (url) {
   return L.icon({
     iconUrl: url || OSM.MARKER_RED,