TransWikia.com

Clipping/cropping/masking a raster tile layer in Mapbox GL JS

Geographic Information Systems Asked by Gareth Jones on January 29, 2021

I’m loading Landsat tiles into a Mapbox GL JS map via an AWS S3 tile server, and this is working OK, but what I’d really like to do is clip the tile layer to a GeoJSON polygon which is loaded in another layer. By this I mean instead of showing the whole image, which in this case covers a huge area, it would just show the part of the image that lies within the boundaries of the GeoJSON polygon – in this case an area of approx 2.5ha. Note that I’m working with irregular polygons too rather than just rectangular bounding boxes.

My first thought was that I might be able to achieve this by somehow setting the raster layer in a fill parameter for the GeoJSON layer, but that doesn’t seem to be possible. Then I thought maybe the GeoJSON layer could be given as a ‘mask’ or ‘clip’ parameter when loading the raster layer, but there doesn’t seem to be any support for this either.

Has anyone else worked out a way to do this? I’d really like to do it with Javascript if possible, but Python may be an option.

One Answer

Use the raster source's bounds: https://www.mapbox.com/mapbox-gl-js/style-spec#sources-raster-bounds

"landsat": {
    "type": "raster",
    "url": "https://some-s3-bucket/{z}/{x}/{y}.png",
    "tileSize": 256,
    "bounds": [ -180, -85.051129, 180, 85.051129 ]
}

An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: [sw.lng, sw.lat, ne.lng, ne.lat]. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL.

You can compute the bounds of an arbitrary GeoJSON using TurfJS bbox.

I don't think this is possible with irregular polygons, although you could invert your GeoJSON polygon, and then style it as a mask that sits above your Landsat tile layer. There is some existing discussion about it that indicates that an "inverted" style won't be built-in, but you can still invert a polygon yourself.

Answered by alphabetasoup on January 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP