diff --git a/src/js/Control/Zoom.js b/src/js/Control/Zoom.js index e0df8f6..e845420 100644 --- a/src/js/Control/Zoom.js +++ b/src/js/Control/Zoom.js @@ -175,24 +175,18 @@ BKGWebMap.Control.createZoom = function () { // Zoom to extent function zoomToExtent() { var extent = ol.extent.createEmpty(); + var projection = map.getView().getProjection(); map.getLayers().forEach(function (layer) { - if (layer instanceof ol.layer.Group) { - layer.getLayers().forEach(function (groupLayer) { - if (groupLayer instanceof ol.layer.Vector) { - ol.extent.extend(extent, groupLayer.getSource().getExtent()); - } else if (layer.extent && layer.extent instanceof Array) { - ol.extent.extend(extent, layer.extent); - } - }); - } else if (layer instanceof ol.layer.Vector) { - ol.extent.extend(extent, layer.getSource().getExtent()); - } else if (layer.extent && layer.extent instanceof Array) { - ol.extent.extend(extent, layer.extent); - } + var layerExtent = BKGWebMap.Util.getLayerExtent(layer, projection); + ol.extent.extend(extent, layerExtent); }); - // TODO: doesn't work with different projections - map.getView().fit(extent, map.getSize()); + + // clip to projection extent? + extent = ol.extent.getIntersection(extent, projection.getExtent()); + + // TODO: check if configured view extent is respected. + map.getView().fit(extent); } // Activate history function diff --git a/src/js/Util.js b/src/js/Util.js index 8c9656a..59b3667 100644 --- a/src/js/Util.js +++ b/src/js/Util.js @@ -661,3 +661,41 @@ if (!('remove' in Element.prototype)) { window.CustomEvent = CustomEvent; }()); + + +/** + * Returns the extent of the given layer. Depending on the layer type the + * access to the extent may vary. + * + * @param {ol.layer.Layer} layer - the layer from which to retrieve the extent + * @param {ol.proj.Projection} projection - optional target projection for layer + * @returns {ol.Extent} + */ +BKGWebMap.Util.getLayerExtent = function (layer, projection) { + var extent; + if (layer instanceof ol.layer.Group) { + extent = ol.extent.createEmpty(); + layer.getLayers().forEach(function (subLayer) { + var subLayerExtent = BKGWebMap.Util.getLayerExtent(subLayer, projection); + ol.extent.extend(extent, subLayerExtent); + }); + return extent; + } + + // layer has no source. e.g. EMPTY + if(layer.getSource() == null) + return ol.extent.createEmpty(); + + if (layer instanceof ol.layer.Vector) { + extent = layer.getSource().getExtent(); + } else if (layer.extent && layer.extent instanceof Array) { + extent = layer.extent; + } + + var srcProjection = layer.getSource().getProjection(); + if (projection && srcProjection != null) { + extent = ol.proj.transformExtent(extent, srcProjection, projection); + } + + return extent; +};