Apply mosaic rules to a mosaic dataset of rasters.

Use case
An image service can use a mosaic rule to mosaic multiple rasters on-the-fly. A mosaic rule can specify which rasters are selected, how the selected rasters are z-ordered, and how overlapping pixels from different rasters at the same location are resolved.
For example, when using the “byAttribute” mosaic method, the values in an attribute field are used to sort the images, and when using the “Center” method, the image closest to the center of the display is positioned as the top image in the mosaic. Additionally, the mosaic operator allows you to define how to resolve the overlapping cells, such as choosing a blending operation.
Specifying mosaic rules is useful for viewing overlapping rasters. For example, using the “By Attribute” mosaic method to sort the rasters based on their acquisition date allows the newest image to be on top. Using the “mean” mosaic operation makes the overlapping areas contain the mean cell values from all the overlapping rasters.
How to use the sample
When the rasters are loaded, choose from a list of preset mosaic rules to apply to the rasters using the dropdown menu at the bottom of the screen. The map will update to display the rasters according to the selected rule.
How it works
- Create an
ImageServiceRasterusing the service’s URL. - Create a
MosaicRuleobject and set it to themosaicRuleproperty of the image service raster. - Create a
RasterLayerfrom the image service raster and add it to the map. - Set the
mosaicMethod,mosaicOperation, and other properties of the mosaic rule object accordingly to specify the rule on the raster dataset.
Relevant API
- ImageServiceRaster
- MosaicMethod
- MosaicOperation
- MosaicRule
- RasterLayer
About the data
This sample uses a raster image service that shows aerial images of Amberg, Germany.
Additional information
The sample applies a hillshade function to a raster produced from the National Land Cover Database, NLCDLandCover2001. You can learn more about the hillshade function in the ArcGIS Pro documentation.
Tags
image service, mosaic method, mosaic rule, raster
Sample Code
/* Copyright 2025 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.applymosaicruletorasters
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport androidx.compose.runtime.Composableimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.applymosaicruletorasters.screens.ApplyMosaicRuleToRastersScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // authentication with an API key or named user is // required to access basemaps and other location services ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN)
enableEdgeToEdge() setContent { SampleAppTheme { ApplyMosaicRuleToRastersApp() } } }
@Composable private fun ApplyMosaicRuleToRastersApp() { Surface(color = MaterialTheme.colorScheme.background) { ApplyMosaicRuleToRastersScreen( sampleName = getString(R.string.apply_mosaic_rule_to_rasters_app_name) ) } }}/* Copyright 2025 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.applymosaicruletorasters.components
import android.app.Applicationimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.geometry.Pointimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.layers.RasterLayerimport com.arcgismaps.raster.ImageServiceRasterimport com.arcgismaps.raster.MosaicMethodimport com.arcgismaps.raster.MosaicOperationimport com.arcgismaps.raster.MosaicRuleimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.launch
/** * ViewModel for the Apply Mosaic Rule to Rasters sample. */class ApplyMosaicRuleToRastersViewModel(app: Application) : AndroidViewModel(app) {
// The map used in the sample, with a topographic basemap. val arcGISMap = ArcGISMap(BasemapStyle.ArcGISTopographic)
// The ImageServiceRaster from the raster image service (Amberg, Germany). private val imageServiceRaster = ImageServiceRaster( url = "https://sampleserver7.arcgisonline.com/server/rest/services/amberg_germany/ImageServer" )
// The RasterLayer that displays the ImageServiceRaster on the map. private val rasterLayer = RasterLayer(imageServiceRaster)
// The list of available mosaic rule types for the dropdown menu. val mosaicRuleTypes = MosaicRuleType.entries
// The currently selected mosaic rule type. private var _selectedRuleType by mutableStateOf(MosaicRuleType.ObjectID) val selectedRuleType get() = _selectedRuleType
// Loading state for the UI, true while the raster layer is loading. var isLoading by mutableStateOf(true) private set
// Message dialog for error handling. val messageDialogVM = MessageDialogViewModel()
// Center point of the raster service (Amberg, Germany), used for recentering the map. private val imageServiceRasterCenter: Point get() { return imageServiceRaster.serviceInfo?.fullExtent?.extent?.center ?: Point( x = 0.0, y = 0.0 ) }
// MapViewProxy for controlling the viewpoint after raster is loaded. val mapViewProxy = MapViewProxy()
init { // Add the raster layer to the map's operational layers. arcGISMap.operationalLayers.add(rasterLayer) // Set the initial mosaic rule (ObjectID/None). imageServiceRaster.mosaicRule = createMosaicRule(MosaicRuleType.ObjectID) updateMosaicRule(_selectedRuleType) }
/** * Updates the mosaic rule on the raster layer to the selected [type]. */ fun updateMosaicRule(type: MosaicRuleType) { _selectedRuleType = type isLoading = true // Set the new mosaic rule on the image service raster. imageServiceRaster.mosaicRule = createMosaicRule(type) // Reload the raster layer and update the center point and viewpoint. viewModelScope.launch { rasterLayer.load().onSuccess { mapViewProxy.setViewpointAnimated( Viewpoint(center = imageServiceRasterCenter, scale = 25000.0) ) isLoading = false }.onFailure { isLoading = false messageDialogVM.showMessageDialog(it) } } }
/** * Helper function to create a [MosaicRule] instance for the given [mosaicRuleType]. */ private fun createMosaicRule(mosaicRuleType: MosaicRuleType): MosaicRule { return MosaicRule().apply { when (mosaicRuleType) { MosaicRuleType.ObjectID -> { // Default mosaic method. mosaicMethod = MosaicMethod.None }
MosaicRuleType.NorthWest -> { // Sorts rasters by northwest location, uses 'first' operation. mosaicMethod = MosaicMethod.Northwest mosaicOperation = MosaicOperation.First }
MosaicRuleType.Center -> { // Sorts rasters by proximity to center, uses 'blend' operation. mosaicMethod = MosaicMethod.Center mosaicOperation = MosaicOperation.Blend }
MosaicRuleType.ByAttribute -> { // Sorts rasters by the OBJECTID attribute. mosaicMethod = MosaicMethod.Attribute sortField = "OBJECTID" }
MosaicRuleType.LockRaster -> { // Locks the mosaic to specific raster IDs. mosaicMethod = MosaicMethod.LockRaster lockRasterIds.addAll(listOf(1, 7, 12)) } } } }}
/** * Enum representing the available preset mosaic rule types for the sample. */enum class MosaicRuleType(val label: String) { ObjectID("Object ID"), NorthWest("North West"), Center("Center"), ByAttribute("By Attribute"), LockRaster("Lock Raster")}/* Copyright 2025 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.applymosaicruletorasters.screens
import android.content.res.Configurationimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.applymosaicruletorasters.components.ApplyMosaicRuleToRastersViewModelimport com.esri.arcgismaps.sample.applymosaicruletorasters.components.MosaicRuleTypeimport com.esri.arcgismaps.sample.sampleslib.components.DropDownMenuBoximport com.esri.arcgismaps.sample.sampleslib.components.LoadingDialogimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SamplePreviewSurfaceimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBar
@Composablefun ApplyMosaicRuleToRastersScreen(sampleName: String) { val mapViewModel: ApplyMosaicRuleToRastersViewModel = viewModel() val selectedRuleType = mapViewModel.selectedRuleType val isLoading = mapViewModel.isLoading
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, content = { padding -> Column( modifier = Modifier .fillMaxSize() .padding(padding), verticalArrangement = Arrangement.SpaceBetween ) { Box(modifier = Modifier.weight(1f)) { MapView( modifier = Modifier.fillMaxSize(), arcGISMap = mapViewModel.arcGISMap, mapViewProxy = mapViewModel.mapViewProxy ) if (isLoading) { LoadingDialog(loadingMessage = "Loading...") } } MosaicRuleOptionsBar( ruleTypes = mapViewModel.mosaicRuleTypes, selectedRuleType = selectedRuleType, onRuleTypeSelected = mapViewModel::updateMosaicRule ) } mapViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } } )}
@Composablefun MosaicRuleOptionsBar( ruleTypes: List<MosaicRuleType>, selectedRuleType: MosaicRuleType, onRuleTypeSelected: (MosaicRuleType) -> Unit) { var selectedIndex by remember(selectedRuleType) { mutableIntStateOf(ruleTypes.indexOf(selectedRuleType)) } Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceAround ) { Text( text = "Mosaic Rule:", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(end = 12.dp) ) DropDownMenuBox( textFieldValue = ruleTypes[selectedIndex].label, textFieldLabel = "Select a mosaic rule", dropDownItemList = ruleTypes.map { it.label }, onIndexSelected = { selectedIndex = it onRuleTypeSelected(ruleTypes[it]) } ) }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun MosaicRuleOptionsBarPreview() { val ruleTypes = MosaicRuleType.entries SamplePreviewSurface { MosaicRuleOptionsBar( ruleTypes = ruleTypes, selectedRuleType = ruleTypes[0], onRuleTypeSelected = {} ) }}