Skip to main content

Work with layers

Add and update layers

You can use the Maps SDK to add more styled data to the map at runtime. There are two key concepts to understand when preparing to add a layer to a style at runtime: layers and sources. Sources contain geographic data. They determine the shape of the features you’re adding to the map and where in the world they belong. Layers contain styling information. They determine how the data in a source should look on the map.

Layers in Mapbox Standard

For Mapbox Standard, you only have access to the layers that you add to the style yourself. To manipulate the Standard basemap, see the Configure a Style section.

A layer is a styled representation of data of a single type (for example polygons, lines, or points) that make up a map style. For example, roads, city labels, and rivers would be three separate layers in a map. There are several layer types (for example fill, line, and symbol). You can read more about layers in the Mapbox Style Specification.

Most layers also require a source. The source provides map data that the Maps SDK can use with a style document to render a visual representation of that data. There are several source types (for example vector tilesets, GeoJSON, and raster data). You can read more about sources in the Mapbox Style Specification.

In the Maps SDK, the StyleManager class exposes the entry point for all methods related to the style object including sources and layers.

Rendering order

Typically, layers are displayed in the order of their declaration, with later layers appearing on top of earlier ones as rendered by the SDK. When using the Mapbox Standard, the display order primarily depends on the layer's slot, while the relative order determines their arrangement within the slot. Layers not associated with slots appear above the entire map, also maintaining their relative order.

If the Globe projection or Terrain is active, the SDK optimizes performance by batching multiple layers together, which may cause layer rearrangements. Layers draped over the globe and terrain, including fill, line, background, hillshade, and raster, are rendered below symbols, regardless of slot placement or the absence of a designated slot.

This means that layers placed with methods such as addLayer(_:layerPosition:) might not appear at the expected LayerPosition for some layer types. If your layer is not positioned in the expected place, try disabling terrain and changing the projection to Mercator.

Add a layer at runtime

To add a new layer to the map at runtime, start by adding a source using the StyleManager’s addSource method. It is important that you add the source for a new layer before attempting to add the layer itself because the source is a required parameter for most layer types.

Then, you’ll use the addLayer(_:layerPosition:) method to add the layer to the style. When adding the style layer, you will specify:

  • A unique ID that you assign to the new layer
  • The layer type (for example fill, line, or symbol)
  • What data to use by referencing a source
  • The appearance of the data by setting various properties (for example color, opacity, and language)

The sample code below illustrates how to add a GeoJSON source and then add and style a line layer that uses the data in that source.

do {
// Make the GeoJSON source with a unique string as the source ID (SOURCE_ID)
// and reference the location of source data
var source = GeoJSONSource(id: "SOURCE_ID")
source.data = .feature(myLineFeature)

// Add the source to the mapView
try mapView.mapboxMap.addSource(source)

// Make the line layer
// Specify a unique string as the layer ID (LAYER_ID)
// and reference the source ID (SOURCE_ID) added above.
let lineLayer = LineLayer(id: "LAYER_ID", source: "SOURCE_ID")

// Add the line layer to the mapView
try mapView.mapboxMap.addLayer(lineLayer)
} catch {
print("Ran into an error adding source or layer: \(error)")
}

The exact available properties available when adding a source and layer varies by source type and layer type. Read more about source types and layer types below.

Update a layer at runtime

You can also update the style of any layer at runtime using the layer's unique layer ID and defining style properties. The sample code below illustrates how to get an existing layer by referencing a layer ID and updating the value of the fillOpacity's value.

do {
// Get an existing layer by referencing its
// unique layer ID (LAYER_ID)
try mapView.mapboxMap.updateLayer(withId: "LAYER_ID", type: FillLayer.self) { layer in
// Update layer properties
layer.fillOpacity = .constant(0.9)
}
} catch {
print("Ran into an error updating the layer: \(error)")
}

The exact available properties available when updating a layer varies by layer type. Read more about layer types below.

Specify order of a layer at runtime for Mapbox Standard

Mapbox Standard uses slots to specify where custom data layers can be added. Slots are predefined locations in the Standard basemap where your layer can be inserted. To add custom layers in the appropriate location in the Standard basemap layer stack, Standard offers 3 carefully designed slots that you can leverage to place your layer. These slots will stay stable, and you can be sure that your own map won't break even as the basemap updates over time.

SlotDescription
bottomAbove polygons (land, landuse, water, etc.)
middleAbove lines (roads, etc.) and behind 3D buildings
topAbove POI labels and behind Place and Transit labels. Designed to be used with the symbol layers
not specifiedAbove all existing layers in the style

Here’s an example of how to assign a slot to a layer:

var layer = LineLayer(id: "line-layer", source: "line-source")
layer.slot = "middle"
mapView.mapboxMap.addLayer(layer)

Make sure to use slots instead of layer ids when inserting a custom layer into the Standard basemap. If you want to order custom layers relative to each other, you can use the layer position in addLayer(_:layerPosition:) method.

Specify order of a layer at runtime for other styles

Map styles contain many individual layers (for example roads, buildings, labels, and more). By default, when you add a new layer to the style, it is placed on top of all the other layers. You can specify where the new layer is positioned relative to existing layers when adding a layer by:

try mapView.mapboxMap.addLayer(populationLayer, layerPosition: .below("settlements"))
  • specifying the desired slot for a layer with slot property to position the layer in the basemap
populationLayer.slot = "bottom"
  • specifying a slot for a layer together with layerPosition to position the layer within the slot
populationLayer.slot = "bottom"
// requires "settlements" layer to be present in the "bottom" slot
try mapView.mapboxMap.addLayer(populationLayer, layerPosition: .below("settlements"))

Remove a layer at runtime

You can remove a layer from a style using Style's removeLayer(withId:).

do {
// Where LAYER_ID is the layer ID for an existing layer
try mapView.mapboxMap.removeLayer(withId: "LAYER_ID")
} catch {
print("Failed to remove layer due to error: \(error)")
}

Source types

Vector

A vector source, VectorSource, is a vector tileset that conforms to the Mapbox Vector Tile format. A vector source contains geographic features (and their data properties) that have already been tiled. Learn more about the benefits of vector tilesets and how they work in the Vector tiles documentation. For vector tiles hosted by Mapbox, the "url" value should be of the form of mapbox://username.tilesetid.

// Create a vector data source.
var source = VectorSource(id: "SOURCE_ID")
// In this case, the tileset is owned by the "mapbox" account
// and "mapbox-terrain-v2" is the tileset ID
source.url = "mapbox://mapbox.mapbox-terrain-v2"
// Add the vector source to the style
try! mapView.mapboxMap.addSource(source)
Note

All style layers that use a vector source must specify a "source-layer" value.

GeoJSON

A GeoJSON source, GeoJSONSource, is data in the form of a JSON object that conforms to the GeoJSON specification. A GeoJSON source is a collection of one or more geographic features, which may be points, lines, and polygons. Data must be provided via a "data" property, whose value can be a URL or inline GeoJSON.

// Attempt to decode GeoJSON from a file named "GradientLine.geojson"
// that is bundled with application.
guard let featureCollection = try? decodeGeoJSON(from: "GradientLine") else { return }
// Create a GeoJSON data source.
var geoJSONSource = GeoJSONSource(id: "SOURCE_ID")
geoJSONSource.data = .featureCollection(featureCollection)
// Add the GeoJSON source to the style
try! mapView.mapboxMap.addSource(geoJSONSource)
Note

See the format of the data used in the sample code above in the Maps SDK example app on GitHub.

Raster

A raster source, RasterSource, is a raster tileset. For raster tiles hosted by Mapbox, the "url" value should be of the form mapbox://tilesetid.

// This URL points to the OpenStreetMap Carto raster tileset.
let sourceUrl = "https://tile.openstreetmap.org/{z}/{x}/{y}.png"
// Create a RasterSource and set the source's "tiles"
// to the OpenStreetMap Carto raster tileset.
var rasterSource = RasterSource(id: "SOURCE_ID")
rasterSource.tiles = [sourceUrl]
// Specify the tile size for the `RasterSource`.
rasterSource.tileSize = 256
// Add the raster source to the style
try! mapView.mapboxMap.addSource(rasterSource)

Raster DEM

A raster DEM source, RasterDemSource, refers to Mapbox Terrain-DEM (mapbox://mapbox.mapbox-terrain-dem-v1), which is the only supported raster DEM source.

// Add a RasterDEMSource
var demSource = RasterDemSource(id: "SOURCE_ID")
// This URL points to the Mapbox-maintained Terrain-DEM tileset
demSource.url = "mapbox://mapbox.mapbox-terrain-dem-v1"
// 514 specifies padded DEM tile and provides better performance than 512 tiles
demSource.tileSize = 514
// Add the raster DEM source to the style
try! mapView.mapboxMap.addSource(demSource)

Image

An image source, ImageSource, is an image that you supply along with geographic coordinates. Specify geographic coordinates in the "coordinates" array as [longitude, latitude] pairs so the SDK knows at what location in the world to place the image. Each coordinate pair in the "coordinates" array represents the image corners listed in clockwise order: top left, top right, bottom right, bottom left.

// Create an ImageSource, which will manage the image displayed
// in the RasterLayer as well as the location of that image on the map
var imageSource = ImageSource(id: "radar-source")
// Set the "coordinates" property to an array of
// longitude, latitude pairs
imageSource.coordinates = [
[-80.425, 46.437],
[-71.516, 46.437],
[-71.516, 37.936],
[-80.425, 37.936]
]
// Get the file path for the first radar image, then set the "url"
// for the ImageSource to that path
let path = Bundle.main.path(forResource: "radar0", ofType: "gif")!
imageSource.url = path
// Add the image source to the style
try! mapView.mapboxMap.addSource(imageSource, id: sourceId)

Layer types

Fill layer

A fill style layer, FillLayer, renders one or more filled (and optionally stroked) polygons on a map. You can use a fill layer to configure the visual appearance of polygon or multipolygon features.

To add a fill layer you need to first add a vector or GeoJSON source that contains polygon data. Then you can use the available properties in the FillLayer class to customize the appearance of the layer (for example, the color, opacity, or pattern).

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext{ _ in
// Specify a unique string as the layer ID (LAYER_ID)
// and reference a valid source via a source ID
var polygonLayer = FillLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
polygonLayer.fillColor = .constant(StyleColor(.green))
polygonLayer.fillOpacity = .constant(0.5)
// Add the fill layer to the style
try! mapView.mapboxMap.addLayer(polygonLayer)
}.store(in: &cancelables)
related
FillLayer

A filled polygon with an optional stroked border.

chevron-right

Line layer

A line style layer, LineLayer, renders one or more stroked polylines on the map. You can use a line layer to configure the visual appearance of polyline or multipolyline features.

To add a line layer, you need to first add a vector or GeoJSON source that contains line data. Then you can use the available properties in the LineLayer class to customize the appearance of the layer (for example, the color, width, or dasharray).

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID ("LAYER_ID")
// and set the source to some source ID (SOURCE_ID).
var lineLayer = LineLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
lineLayer.lineColor = .constant(StyleColor(.red))
lineLayer.lineCap = .constant(.round)
// Add the line layer to the map.
try! mapView.mapboxMap.addLayer(lineLayer)
}.store(in: &cancelables)
related
LineLayer

A stroked line.

chevron-right

Symbol layer

A symbol style layer, SymbolLayer, renders icon and text labels at points or along lines on a map. You can use a symbol layer to configure the visual appearance of labels for features in vector tiles.

To add a symbol layer, you need to first add a vector or GeoJSON source that contains point data. If you want to use icons in this layer, you also need to add images to the style before adding the layer. Then you can use the available properties in the SymbolLayer class to customize the appearance of the layer.

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID ("LAYER_ID")
// and set the source to some source ID (SOURCE_ID).
var symbolLayer = SymbolLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
// "city_name" refers to a data property for features in the
// source data
symbolLayer.textField = .expression(Exp(.get) { "city_name" })
symbolLayer.textSize = .constant(12)
// Add the symbol layer to the map.
try! mapView.mapboxMap.addLayer(symbolLayer)
}.store(in: &cancelables)
related
SymbolLayer

An icon or a text label.

chevron-right

Circle layer

A circle style layer, CircleLayer, renders one or more filled circles on a map. You can use a circle layer to configure the visual appearance of point or point collection features in vector tiles. A circle layer renders circles whose radii are measured in screen units.

To add a circle layer, you need to first add a vector or GeoJSON source that contains point data. Then you can use the available properties in the CircleLayer class to customize the appearance of the layer (for example, radius, color, or offset).

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID ("LAYER_ID")
// and set the source to some source ID (SOURCE_ID).
var circleLayer = CircleLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
circleLayer.circleRadius = .constant(8)
circleLayer.circleColor = .constant(StyleColor(.red))
// Add the circle layer to the map.
try! mapView.mapboxMap.addLayer(circleLayer)
}.store(in: &cancelables)
related
CircleLayer

A filled circle.

chevron-right

Fill extrusion layer

A fill-extrusion, FillExtrusionLayer, style layer renders one or more filled (and optionally stroked) extruded (3D) polygons on a map. You can use a fill-extrusion layer to configure the extrusion and visual appearance of polygon or multipolygon features.

To add a fill extrusion layer, you need to first add a vector or GeoJSON source that contains polygon data. Often you will want the data to contain a data property that you will use to determine the height of extrusion of each feature. This may be a physical height in meters or a way to illustrate a non-physical attribute of the area like population in Census blocks. Once you've added an appropriate source, you can use the available properties in the FillExtrusionLayer class to customize the appearance of the layer (for example, the height, opacity, or color).

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID ("LAYER_ID")
// Set the source to some source ID, for example "composite"
// is the source for the Mapbox Light style
var fillExtrusionLayer = FillExtrusionLayer(id: "LAYER_ID", source: "composite")
// And "building is the source layer in the Mapbox Light style
// that contains polygon building data
fillExtrusionLayer.sourceLayer = "building"
// Set some style properties
fillExtrusionLayer.fillExtrusionColor = .constant(StyleColor(.lightGray))
fillExtrusionLayer.fillExtrusionOpacity = .constant(0.6)
// Where "height" is the data property in the "building" source
// layer that contains the height of each building
fillExtrusionLayer.fillExtrusionHeight = .expression(Exp(.get) { "height" })
// Add the fill extrusion layer to the map.
try! mapView.mapboxMap.addLayer(fillExtrusionLayer)
}.store(in: &cancelables)
related
FillExtrusionLayer

An extruded (3D) polygon.

chevron-right

Hillshade layer

A hillshade style layer, HillshadeLayer, renders digital elevation model (DEM) data on the client-side.

The implementation only supports sources comprised of Mapbox Terrain RGB or Mapzen Terrarium tiles. Once you've added an appropriate source, you can use the available properties in the HillshadeLayer class to customize the appearance of the layer.

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Create a RasterDEMSource.
var source = RasterDemSource(id: "hillshade-source")
source.url = "mapbox://mapbox.mapbox-terrain-dem-v1"
source.tileSize = 512
source.maxzoom = 14.0

// Create a hillshade layer with a unique layer ID.
let layer = HillshadeLayer(id: "hillshade-layer", source: source.id)

try! mapView.mapboxMap.addSource(source)
try! mapView.mapboxMap.addLayer(layer)
}.store(in: &cancelables)
related
HillshadeLayer

Client-side hillshading visualization based on DEM data. The implementation only supports Mapbox Terrain RGB and Mapzen Terrarium tiles.

chevron-right

Heatmap layer

A heatmap style layer, HeatmapLayer, renders a range of colors to represent the density of points in an area.

To add a heatmap layer, you need to first add a vector or GeoJSON source that contains point data. Then you can use the available properties in the HeatmapLayer class to customize the appearance of the layer.

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Create the heatmap layer using the specified layer and source IDs.
var layer = HeatmapLayer(id: "earthquake-heatmap-layer", source: "earthquake-source")
// Set the heatmap layer's color property.
layer.heatmapColor = .expression(
Exp(.interpolate) {
Exp(.linear)
Exp(.heatmapDensity)
0
UIColor.clear
0.2
UIColor.blue
0.4
UIColor.green
0.6
UIColor.yellow
0.8
UIColor.orange
1.0
UIColor.red
})

// Add the heatmap layer to the map.
try! mapView.mapboxMap.addLayer(layer)
}.store(in: &cancelables)
related
HeatmapLayer

A heatmap.

chevron-right

Raster layer

A raster style layer, RasterLayer, renders raster tiles on a map. You can use a raster layer to configure the color parameters of raster tiles.

To add a raster layer, you need to first add a raster source. Then you can use the available properties in the RasterLayer class to customize the appearance of the layer.

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID ("LAYER_ID")
// and set the source to some source ID (SOURCE_ID).
var rasterLayer = RasterLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
rasterLayer.rasterFadeDuration = .constant(0)
// Add the raster layer to the map.
try! mapView.mapboxMap.addLayer(rasterLayer)
}.store(in: &cancelables)
related
RasterLayer

Raster map textures such as satellite imagery.

chevron-right

Sky layer

A sky style layer, SkyLayer, renders a stylized spherical dome that encompasses the entire map and is automatically rendered behind all layers. This can be used to fill the area above the horizon with a simulated sky that illustrates a particular time-of-day, or stylized custom gradients.

You can use the available properties in the SkyLayer class to customize the appearance of the layer.

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID ("LAYER_ID")
var skyLayer = SkyLayer(id: "LAYER_ID")
// Set some style properties
skyLayer.skyType = .constant(.gradient)
let azimuthalAngle: Double = 0
let polarAngle: Double = 90
skyLayer.skyAtmosphereSun = .constant([azimuthalAngle, polarAngle])
// Add the sky layer to the map.
try! mapView.mapboxMap.addLayer(skyLayer)
}.store(in: &cancelables)
related
SkyLayer

A spherical dome around the map that is always rendered behind all other layers.

chevron-right

Background layer

The background style layer, BackgroundLayer, covers the entire map. Use a background style layer to configure a color or pattern to show below all other map content. If the background layer is transparent or omitted from the style, any part of the map view that does not show another style layer is transparent.

You can use the available properties in the BackgroundLayer class to customize the appearance of the layer.

// Wait for the map to load its style before adding data.
mapView.mapboxMap.onMapLoaded.observeNext { _ in
// Specify a unique string as the layer ID (LAYER_ID)
var layer = BackgroundLayer(id: "background-layer")
layer.backgroundColor = .constant(StyleColor(.white))
}.store(in: &cancelables)
related
BackgroundLayer

The background color or pattern of the map.

chevron-right
Was this page helpful?