Zum Inhalt

Stilwechsel (Android)

Wechseln Sie zur Laufzeit zwischen SmartMaps-Stilen, zum Beispiel um den Dark Mode zu unterstützen.

MapSession erforderlich

Denken Sie daran, die MapSession in Ihre App zu integrieren. Die MapSession muss alle 10 Minuten aufgerufen werden, solange die Karte aktiv ist.

Automatischer Dark Mode

import android.content.res.Configuration

class MainActivity : AppCompatActivity() {
    private lateinit var mapView: MapView
    private val apiKey = "[INSERT API-KEY]"

    private fun getStyleUrl(): String {
        val isDarkMode = resources.configuration.uiMode and
            Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES

        val styleName = if (isDarkMode) "dark" else "light"
        return "https://tiles.smartmaps.cloud/styles/v1/smartmaps/$styleName/style.json?apiKey=$apiKey&channel=app"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MapLibre.getInstance(this)
        setContentView(R.layout.activity_main)

        mapView = findViewById(R.id.mapView)
        mapView.onCreate(savedInstanceState)
        mapView.getMapAsync { map ->
            map.setStyle(getStyleUrl())
            map.cameraPosition = CameraPosition.Builder()
                .target(LatLng(49.0069, 8.4037))
                .zoom(12.0)
                .build()
        }
    }

    // Re-apply style when configuration changes
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        mapView.getMapAsync { map ->
            map.setStyle(getStyleUrl())
        }
    }

    // Lifecycle methods
    override fun onStart() { super.onStart(); mapView.onStart() }
    override fun onResume() { super.onResume(); mapView.onResume() }
    override fun onPause() { super.onPause(); mapView.onPause() }
    override fun onStop() { super.onStop(); mapView.onStop() }
    override fun onDestroy() { super.onDestroy(); mapView.onDestroy() }
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mapView.onSaveInstanceState(outState)
    }
    override fun onLowMemory() { super.onLowMemory(); mapView.onLowMemory() }
}

Stilauswahl mit Buttons

mapView.getMapAsync { map ->
    map.setStyle(
        "https://tiles.smartmaps.cloud/styles/v1/smartmaps/light/style.json?apiKey=$apiKey&channel=app"
    )

    val styles = mapOf(
        R.id.btnLight to "light",
        R.id.btnDark to "dark",
        R.id.btnGrey to "grey",
        R.id.btnEssential to "essential",
        R.id.btnAccessible to "accessible",
        R.id.btnSatellite to "satellite"
    )

    styles.forEach { (buttonId, styleName) ->
        findViewById<Button>(buttonId).setOnClickListener {
            map.setStyle(
                "https://tiles.smartmaps.cloud/styles/v1/smartmaps/$styleName/style.json?apiKey=$apiKey&channel=app"
            )
        }
    }
}