Skip to content

Apply mosaic rule to rasters

View on GitHubSample viewer app

Apply mosaic rules to a mosaic dataset of rasters.

Image of Apply mosaic rule to rasters sample

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

  1. Create an ImageServiceRaster using the service's URL.
  2. Create a MosaicRule object and set it to the mosaicRule property of the image service raster.
  3. Create a RasterLayer from the image service raster and add it to the map.
  4. 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

ApplyMosaicRuleToRastersViewModel.ktApplyMosaicRuleToRastersViewModel.ktMainActivity.ktApplyMosaicRuleToRastersScreen.kt
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/* 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.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.geometry.Point
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.layers.RasterLayer
import com.arcgismaps.raster.ImageServiceRaster
import com.arcgismaps.raster.MosaicMethod
import com.arcgismaps.raster.MosaicOperation
import com.arcgismaps.raster.MosaicRule
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import 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")
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.