diff --git a/app/assets/javascripts/leaflet.map.js b/app/assets/javascripts/leaflet.map.js index 1e9174efa6e..e2bfd64a5a3 100644 --- a/app/assets/javascripts/leaflet.map.js +++ b/app/assets/javascripts/leaflet.map.js @@ -116,20 +116,19 @@ L.OSM.Map = L.Map.extend({ }, updateLayers: function (layerParam) { - var layers = layerParam || "O", - layersAdded = ""; - - for (let 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 () { @@ -143,11 +142,8 @@ L.OSM.Map = L.Map.extend({ }, getMapBaseLayerId: function () { - var baseLayerId; - this.eachLayer(function (layer) { - if (layer.options && layer.options.keyid) baseLayerId = layer.options.keyid; - }); - return baseLayerId; + const layer = this.getMapBaseLayer(); + if (layer) return layer.options.layerId; }, getMapBaseLayer: function () { diff --git a/test/javascripts/osm_test.js b/test/javascripts/osm_test.js index c5be6b5f6a5..b6f1adedc0f 100644 --- a/test/javascripts/osm_test.js +++ b/test/javascripts/osm_test.js @@ -339,7 +339,7 @@ describe("OSM", function () { it("creates a location cookie value", function () { $("body").append("
"); const map = new L.OSM.Map("map", { center: [57.6247, -3.6845], zoom: 9 }); - map.updateLayers(""); + map.updateLayers("M"); expect(OSM.locationCookie(map)).to.eq("-3.685|57.625|9|M"); $("#map").remove(); }); @@ -347,7 +347,7 @@ describe("OSM", function () { it("respects zoomPrecision", function () { $("body").append("
"); const map = new L.OSM.Map("map", { center: [57.6247, -3.6845], zoom: 9 }); - map.updateLayers(""); + map.updateLayers("M"); expect(OSM.locationCookie(map)).to.eq("-3.685|57.625|9|M"); // map.setZoom() doesn't update the zoom level for some reason // using map._zoom here to update the zoom level manually