Work with 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.

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.

Style methods

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

Add a layer at runtime

To add a new layer to the map at runtime, start by adding a source using the Style’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
  var source = GeoJSONSource()  
  source.data = .feature(myLineFeature)

  // Add the source to the mapView
  // Specify a unique string as the source ID (SOURCE_ID)
  // and reference the location of source data
  try mapView.mapboxMap.style.addSource(source, id: "SOURCE_ID")

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

  // Add the line layer to the mapView
  try mapView.mapboxMap.style.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.style.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

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 populating the layerPosition argument in the addLayer(_:layerPosition:) method.

The sample code below illustrates how to add a new layer with the ID "population" below the layer with the ID "state-labels".

do {
  let populationLayer = FillLayer(id: "population")
  populationLayer.source = "population-source"
  // Add the population layer created above to the mapView and position it below the already existing "state-labels" layer.
  try mapView.mapboxMap.style.addLayer(populationLayer, layerPosition: .below("state-labels"))
} catch {
  print("Ran into an error adding the population layer: \(error)")
}

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.style.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.

// Specify a unique string as the source ID (SOURCE_ID)
let sourceIdentifier = "SOURCE_ID"
var source = VectorSource()
// 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.style.addSource(source, id: sourceIdentifier)
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 }
// Specify a unique string as the source ID (SOURCE_ID)
let geoJSONDataSourceIdentifier = "SOURCE_ID"
// Create a GeoJSON data source.
var geoJSONSource = GeoJSONSource()
geoJSONSource.data = .featureCollection(featureCollection)
// Add the GeoJSON source to the style
try! mapView.mapboxMap.style.addSource(geoJSONSource, id: geoJSONDataSourceIdentifier)
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.

// Specify a unique string as the source ID (SOURCE_ID)
let sourceIdentifier = "SOURCE_ID"
// This URL points to raster tiles designed by Stamen Design.
let sourceUrl = "https://stamen-tiles.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.jpg"
// Create a RasterSource and set the source's "tiles"
// to the Stamen watercolor raster tiles.
var rasterSource = RasterSource()
rasterSource.tiles = [sourceUrl]
// Specify the tile size for the `RasterSource`.
rasterSource.tileSize = 256
// Add the raster source to the style
try! mapView.mapboxMap.style.addSource(rasterSource, id: sourceId)

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.

// Specify a unique string as the source ID (SOURCE_ID)
let sourceIdentifier = "SOURCE_ID"
// Add a RasterDEMSource
var demSource = RasterDemSource()
// 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.style.addSource(demSource, id: sourceIdentifier)

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.

// Specify a unique string as the source ID (SOURCE_ID)
var sourceId = "radar-source"
// 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()
// 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.style.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.onNext(.mapLoaded) { _ 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")
  polygonLayer.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.style.addLayer(fillLayer)
}
related
FillLayer

A filled polygon with an optional stroked border.

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.onNext(.mapLoaded) { _ 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")
  lineLayer.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.style.addLayer(lineLayer)
}
related
LineLayer

A stroked line.

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.onNext(.mapLoaded) { _ 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")
  symbolLayer.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.style.addLayer(symbolLayer)
}
related
SymbolLayer

An icon or a text label.

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.onNext(.mapLoaded) { _ 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")
  circleLayer.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.style.addLayer(circleLayer)
}
related
CircleLayer

A filled circle.

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.onNext(.mapLoaded) { _ in
  // Specify a unique string as the layer ID ("LAYER_ID")
  var fillExtrusionLayer = FillExtrusionLayer(id: "LAYER_ID")
  // Set the source to some source ID, for example "composite"
  // is the source for the Mapbox Light style
  fillExtrusionLayer.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.style.addLayer(fillExtrusionLayer)
}
related
FillExtrusionLayer

An extruded (3D) polygon.

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.


  // Specify a unique string as the layer ID (LAYER_ID)
  // and assign the source ID added above.

    // set a few properties

related
HillshadeLayer

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


let sourceId = "hillshade-source"

// Create a RasterDEMSource.
var source = RasterDemSource()
source.url = "mapbox://mapbox.mapbox-terrain-dem-v1"
source.tileSize = 512
source.maxzoom = 14.0

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

try! style.addSource(source, id: sourceId)
try! style.addLayer(layer)

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.


 let sourceId = "earthquake-source"

 // Create the heatmap layer using the specified layer and source IDs.
 var layer = HeatmapLayer(id: "earthquake-heatmap-layer")
 layer.source = sourceId
 // 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! style.addLayer(layer)

related
HeatmapLayer

A heatmap.

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.onNext(.mapLoaded) { _ 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")
  fillExtrusionLayer.source = "SOURCE_ID"
  // Set some style properties
  rasterLayer.rasterFadeDuration = .constant(0)
  // Add the raster layer to the map.
  try! mapView.mapboxMap.style.addLayer(rasterLayer)
}
related
RasterLayer

Raster map textures such as satellite imagery.

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.onNext(.mapLoaded) { _ in
  // Specify a unique string as the layer ID ("LAYER_ID")
  // and set the source to some source ID (SOURCE_ID).
  var skyLayer = SkyLayer(id: "LAYER_ID")
  skyLayer.source = "SOURCE_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.style.addLayer(skyLayer)
}
related
SkyLayer

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

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.


  // Specify a unique string as the layer ID (LAYER_ID)
  // and assign the source ID added above.
  var layer = BackgroundLayer(id: "background-layer")
  layer.source = sourceId
  layer.backgroundColor = .constant(StyleColor(.white))

related
BackgroundLayer

The background color or pattern of the map.