Raw Expression
This example showcases how to use an expression to adjust the style of a map through the Value API in the Mapbox Maps SDK for Android.
The code below manipulates the water fill layer by adjusting the hue of the fill color according to the zoom level. The assigned expression
uses the interpolate
operator to smoothly transition between different hues as the zoom changes.
Android Examples App Available
This example code is part of the Maps SDK for Android Examples App, a working Android project available on GitHub. Android 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 Android Examples App tutorial for step-by-step instructions.
package com.mapbox.maps.testapp.examples
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.maps.MapInitOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.extension.style.expressions.generated.Expression
import com.mapbox.maps.extension.style.layers.generated.FillLayer
import com.mapbox.maps.extension.style.layers.getLayerAs
/**
* Example showcasing raw expression support through the Value API.
* This example manipulates the water fill layer of mapbox-streets to:
* ```
* {
* "id": "water",
* "type": "fill",
* "source": "composite",
* "source-layer": "water",
* "layout": {},
* "paint": {
* "fill-color": [
* "interpolate",
* ["linear"],
* ["zoom"],
* 0, "hsl(103, 80%, 70%)",
* 8.53, "hsl(360, 80%, 70%)",
* 22, "hsl(196, 80%, 70%)"
* ]
* }
* }
* ```
*/
class RawExpressionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val mapView = MapView(this, MapInitOptions(context = this, styleUri = Style.MAPBOX_STREETS))
setContentView(mapView)
mapView.mapboxMap.getStyle {
addExpressionToStyle(it)
}
}
private fun addExpressionToStyle(style: Style) {
style.getLayerAs<FillLayer>("water")?.fillColor(
Expression.fromRaw(
"""
[
"interpolate",
["linear"],
["zoom"],
0, "hsl(103, 80%, 70%)",
8.53, "hsl(360, 80%, 70%)",
22, "hsl(196, 80%, 70%)"
]
""".trimIndent()
)
)
}
}
Was this example helpful?