メインコンテンツまでスキップ

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 and Standard Satellite, 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 or Mapbox Standard Satellite, 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.


// In SwiftUI, you can add sources and layers directly to the Map
struct CustomLayers: View {
@State var darkMode = false

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

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

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

In UIKit, you can 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. In SwiftUI, use states directly in a layer definitions.


struct CustomLayers: View {
@State var fillOpacity = 0.9
var body: some View {
Map {
GeoJSONSource(id: "SOURCE_ID")
.data(.feature(myLineFeature))

LineLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Use state directly in the layer definition.
.fillOpacity(fillOpacity)
}
}
}
GUIDE
Declarative Styling Guide

In SwiftUI, you define styles using the new Declarative Styling API. The new approach makes working with styles much easier and can be used in UIKit applications as well. Learn more in the guide.

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 and Standard Satellite

Mapbox Standard and Standard Satellite uses slots to specify where custom data layers can be added. Slots are predefined locations in the Standard or Standard Satellite basemap where your layer can be inserted. To add custom layers in the appropriate location in the Standard or Standard Satellite basemap layer stack, Standard and Standard Satellite 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:


LineLayer(id: "line-layer", source: "line-source")
.slot(.middle)

Make sure to use slots instead of layer ids when inserting a custom layer into the Standard or Standard Satellite 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"))

In SwiftUI, the layer order is defined by position in the Map content and specified slot. If the slot is not specified, the layers are displayed on top of the basemap layers. In the

// SwiftUI
Map {
FillLayer(id: "A", source: "source-A")
FillLayer(id: "B", source: "source-B")

FillLayer(id: "C", source: "source-C")
.slot(.bottom)
FillLayer(id: "D", source: "source-D")
.slot(.bottom)

FillLayer(id: "E", source: "source-E")
}

In this example, the layers C and D will be displayed in the "bottom" slot of the basemap. The layer D will render above layer C. Layers A, B, and E don't specify a slot, so they render above the basemap with layer E above layer B, and layer B above layer A.

Remove a layer at runtime

You can remove a layer from a style using Style's removeLayer(withId:). In SwiftUI, you can put the layer definition into a condition.


struct RouteView: View {
@State var showRoute = true
var body: some View {
Map {
if showRoute {
LineLayer(id: "route-layer", source: "route-source")
}
}
}
}

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.


Map {
// Create a vector data source.
VectorSource(id: "SOURCE_ID")
// In this case, the tileset is owned by the "mapbox" account
// and "mapbox-terrain-v2" is the tileset ID
.url("mapbox://mapbox.mapbox-terrain-v2")
}

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.


struct GeoJSONSourceView: View {
@State var featureCollection: FeatureCollection?
var body: some View {
Map {
if let featureCollection {
// Create a GeoJSON data source.
GeoJSONSource(id: "SOURCE_ID")
.featureCollection(featureCollection)
}
}
.onAppear {
// Attempt to decode GeoJSON from a file named "GradientLine.geojson"
// that is bundled with application.
featureCollection = try? decodeGeoJSON(from: "GradientLine")
}
}
}
GUIDE
GeoJSON and Declarative Styling performance

Learn how to optimize performance when using declarative styling with large GeoJSON objects.

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.


Map {
RasterSource(id: "SOURCE_ID")
// Create a RasterSource and set the source's "tiles"
// to the OpenStreetMap Carto raster tileset.
.tiles(["https://tile.openstreetmap.org/{z}/{x}/{y}.png"])
// Specify the tile size for the RasterSource.
.tileSize(256)
}

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.


Map {
// Add a RasterDEMSource
RasterDEMSource(id: "SOURCE_ID")
// This URL points to the Mapbox-maintained Terrain-DEM tileset
.url("mapbox://mapbox.mapbox-terrain-dem-v1")
// 514 specifies padded DEM tile and provides better performance than 512 tiles
.tileSize(514)
}

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.


Map {
// Create an ImageSource, which will manage the image displayed
// in the RasterLayer as well as the location of that image on the map
ImageSource(id: "radar-source")
// Set the "coordinates" property to an array of longitude, latitude pairs
.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
.url(Bundle.main.path(forResource: "radar0", ofType: "gif")!)
}

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


Map {
// Specify a unique string as the layer ID (LAYER_ID)
// and reference a valid source via a source ID
FillLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
.fillColor(.green)
.fillOpacity(0.5)
}
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).


Map {
// Specify a unique string as the layer ID (LAYER_ID)
// and reference a valid source via a source ID
LineLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
.lineColor(.red)
.lineCap(.round)
}
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.


Map {
// Specify a unique string as the layer ID (LAYER_ID)
// and reference a valid source via a source ID
SymbolLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
// "city_name" refers to a data property for features in the
// source data
.textField(Exp(.get) { "city_name" })
.textSize(12)
}
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).


Map {
// Specify a unique string as the layer ID (LAYER_ID)
// and reference a valid source via a source ID
CircleLayer(id: "LAYER_ID", source: "SOURCE_ID")
// Set some style properties
.circleRadius(8)
.circleColor(.red)
}
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).


Map {
// 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
FillExtrusionLayer(id: "LAYER_ID", source: "composite")
// And "building is the source layer in the Mapbox Light style
// that contains polygon building data
.sourceLayer("building")
// Set some style properties
.fillExtrusionColor(.lightGray)
.fillExtrusionOpacity(0.6)
// Where "height" is the data property in the "building" source
// layer that contains the height of each building
.fillExtrusionHeight(Exp(.get) { "height" })
}.mapStyle(.light)
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.


Map {
// Create a RasterDEMSource.
RasterDemSource(id: "hillshade-source")
.url("mapbox://mapbox.mapbox-terrain-dem-v1")
.tileSize(512)
.maxzoom(14.0)

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

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

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.


Map {
// Create the heatmap layer using the specified layer and source IDs.
HeatmapLayer(id: "earthquake-heatmap-layer", source: "earthquake-source")
// Set the heatmap layer's color property.
.heatmapColor(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
})
}
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.


Map {
// 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
.rasterFadeDuration(0)
}
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.


Map {
// Specify a unique string as the layer ID ("LAYER_ID")
SkyLayer(id: "LAYER_ID")
// Set some style properties
.skyType(.gradient)
.skyAtmosphereSun(azimuthal: 0, polar: 90)
}
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.


Map {
// Specify a unique string as the layer ID ("LAYER_ID")
BackgroundLayer(id: "background-layer")
// Set some style properties
.backgroundColor(.white)
}
RELATED
BackgroundLayer

The background color or pattern of the map.

このpageは役に立ちましたか?