Interpolate colors between zoom level
This example demonstrates the smooth transition of colors on the map based on zoom levels by using a color expression in an application build with the Mapbox Maps SDK for iOS. The code initializes a MapView
centered over the United States and waits for the map style to load before adding data. The JSON expression ["interpolate", ["linear"], ["zoom"], 0, "hsl(0, 79%, 53%)", 14, "hsl(233, 80%, 47%)"]
is transformed into a Swift representation to interpolate colors based on zoom levels. Two color stops at zoom levels 0 and 14 are defined using UIColor
.
The interpolation expression is constructed using Exp
instances and then encoded into JSON format. Finally, the color interpolation expression is applied to the land
layer's background color property on the map.
This example code is part of the Maps SDK for iOS Examples App, a working iOS project available on Github. iOS developers are encouraged to run the examples app locally to interact with this example in an emulator and explore other features of the Maps SDK.
See our Run the Maps SDK for iOS Examples App tutorial for step-by-step instructions.
import UIKit
import MapboxMaps
final class ViewController: UIViewController {
private var mapView: MapView!
private var cancelables = Set<AnyCancelable>()
override func viewDidLoad() {
super.viewDidLoad()
// Center the map over the United States.
let centerCoordinate = CLLocationCoordinate2D(latitude: 40.58058466412761,
longitude: -97.734375)
let options = MapInitOptions(cameraOptions: CameraOptions(center: centerCoordinate, zoom: 3), styleURI: .streets)
mapView = MapView(frame: view.bounds, mapInitOptions: options)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(mapView)
// Allows the view controller to receive information about map events.
mapView.mapboxMap.onMapLoaded.observeNext { [weak self] _ in
self?.setupExample()
}.store(in: &cancelables)
}
// Wait for the style to load before adding data to it.
func setupExample() {
/**
This JSON expression is transformed to swift below:
[
"interpolate",
["linear"],
["zoom"],
0,
"hsl(0, 79%, 53%)",
14,
"hsl(233, 80%, 47%)"
]
*/
let stops: [Double: UIColor] = [
0: .red,
14: .blue
]
let exp = Exp(.interpolate) {
Exp(.linear)
Exp(.zoom)
stops
}
if let data = try? JSONEncoder().encode(exp.self),
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) {
try! mapView.mapboxMap.setLayerProperty(for: "land",
property: "background-color",
value: jsonObject)
}
}
}