I'm trying to clip a layer by vector in OpenLayers 5. I've found this answer that kind of works, but it does not solve my specific problem, namely bandwidth.

I'm combining WMTS services from two different countries, and would like to block one service from serving tiles over the other country's area, since that just wastes bandwidth. The countries are Norway and Sweden, so simple bounds won't help me (the border goes on the diagonal of any bounding box).

1 Answer 1


You could customise the tileUrlFunction to only return a url if the tile extent intersects the country's geometry

var defaultUrlFunction = source.getTileUrlFunction();
source.setTileUrlFunction( function(tileCoord, pixelRatio, projection) {
    if (countryGeometry.intersectsExtent(this.getTileGrid().getTileCoordExtent(tileCoord))) {
        return defaultUrlFunction(tileCoord, pixelRatio, projection);
  • This worked beautifully. I had to make some changes as my vector was a vectorLayer: var seUrlFunction = seXYZ.getSource().getTileUrlFunction(); seXYZ.getSource().setTileUrlFunction(function(tileCoord, pixelRatio, projection) { for (var feature of seBounds.getSource().getFeatures()) { var featureIntersects = feature.getGeometry() .intersectsExtent(this.getTileGrid() .getTileCoordExtent(tileCoord)); if (featureIntersects) { return seUrlFunction(tileCoord, pixelRatio, projection); } }; }); Dec 9, 2018 at 23:56
  • I've just had a custom url function stop working after moving to the latest version of OL. I fixed it by changing to var defaultUrlFunction = source.getTileUrlFunction().bind(source); It was a TileWMS source but be aware it might affect other sources in the future.
    – Mike
    Dec 18, 2018 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.