# Perform spatial operations

View inJavaKotlin
View on GitHub
Sample viewer app

Find the union, intersection, or difference of two geometries.

## Use case

The different spatial operations (union, difference, symmetric difference, and intersection) can be used for a variety of spatial analyses. For example, government authorities may use the intersect operation to determine whether a proposed road cuts through a restricted piece of land such as a nature reserve or a private property.

When these operations are chained together, they become even more powerful. An analysis of food deserts within an urban area might begin by union-ing service areas of grocery stores, farmer's markets, and food co-ops. Taking the difference between this single geometry of all services areas and that of a polygon delineating a neighborhood would reveal the areas within that neighborhood where access to healthy, whole foods may not exist.

## How to use the sample

Select a spatial operation from the overflow menu. When an operation is selected, the resulting geometry is shown in red.

## How it works

1. Create two `GraphicsOverlay`s, one to show polygons and another to show the relationships between them.
2. Define a `PointCollection` of each `Geometry`.
3. Add the overlapping polygons to a graphics overlay.
4. Perform spatial relationships between the polygons by using the appropriate operation:
• `GeometryEngine.union(geometry1, geometry2)` - This method returns the two geometries united together as one geometry.
• `GeometryEngine.difference(geometry1, geometry2)` - This method returns any part of Geometry2 that does not intersect Geometry1.
• `GeometryEngine.symmetricDifference(geometry1, geometry2)` - This method returns any part of Geometry1 or Geometry2 which do not intersect.
• `GeometryEngine.intersection(geometry1, geometry2)` - This method returns the intersection of Geometry1 and Geometry2.
5. Add the resultant geometry to a new `Graphic` and display it by adding it to the second `GraphicsOverlay`.

## Relevant API

• Geometry
• GeometryEngine
• GeometryEngine.difference
• GeometryEngine.intersection
• GeometryEngine.symmetricDifference
• GeometryEngine.union
• Graphic
• GraphicsOverlay

## Tags

analysis, combine, difference, geometry, intersection, merge, polygon, union

## Sample Code

MainActivity.kt
Use dark colors for code blocksCopy

``````/*
*
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*
*/

package com.esri.arcgisruntime.sample.performspatialoperations

import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Geometry
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Part
import com.esri.arcgisruntime.geometry.PartCollection
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.PointCollection
import com.esri.arcgisruntime.geometry.Polygon
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.performspatialoperations.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol

class MainActivity : AppCompatActivity() {

private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}

private val mapView: MapView by lazy {
activityMainBinding.mapView
}

private val inputGeometryGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private val resultGeometryGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }

// simple black line symbol for outlines
private val lineSymbol = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1f)
private val resultFillSymbol = SimpleFillSymbol(
SimpleFillSymbol.Style.SOLID, Color.RED, lineSymbol
)
private lateinit var inputPolygon1: Polygon
private lateinit var inputPolygon2: Polygon

// the spatial operation switching menu items.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)

// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

mapView.apply {
// create an ArcGISMap with a light gray basemap
map = ArcGISMap(BasemapStyle.ARCGIS_LIGHT_GRAY)

// create graphics overlays to show the inputs and results of the spatial operation

}

// create input polygons and add graphics to display these polygons in an overlay
createPolygons()

// center the map view on the input geometries
val envelope = GeometryEngine.union(inputPolygon1, inputPolygon2).extent
mapView.setViewpointGeometryAsync(envelope, 20.0)
}

private fun showGeometry(resultGeometry: Geometry) {
// add a graphic from the result geometry, showing result in red (0xFFE91F1F)
val graphic = Graphic(resultGeometry, resultFillSymbol).also {
// select the result to highlight it
it.isSelected = true
}

}

private fun createPolygons() {
// create input polygon 1
inputPolygon1 = Polygon(PointCollection(SpatialReferences.getWebMercator()).apply {

})

// create and add a blue graphic to show input polygon 1
val blueFill = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.BLUE, lineSymbol)

// outer ring
val outerRing = Part(PointCollection(SpatialReferences.getWebMercator()).apply {
})

// inner ring
val innerRing = Part(PointCollection(SpatialReferences.getWebMercator()).apply {
})

// add both parts (rings) to a part collection and create a geometry from it
PartCollection(outerRing).run {
inputPolygon2 = Polygon(this)
}

// create and add a green graphic to show input polygon 2
val greenFill = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.GREEN, lineSymbol)

}

// inflate the menu; this adds items to the action bar if it is present.

// Get the menu items that perform spatial operations.

// set the 'no-op' menu item checked by default

return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
val itemId = item.itemId

// clear previous operation result
resultGeometryGraphicsOverlay.graphics.clear()

// perform spatial operations and add results as graphics, depending on the option selected
when (itemId) {
R.id.action_no_operation -> {
// no spatial operation - graphics have been cleared previously
return true
}
R.id.action_intersection -> {
showGeometry(GeometryEngine.intersection(inputPolygon1, inputPolygon2))
return true
}
R.id.action_union -> {
showGeometry(GeometryEngine.union(inputPolygon1, inputPolygon2))
return true
}
R.id.action_difference -> {
// note that the difference method gives different results depending on the order of input geometries
showGeometry(GeometryEngine.difference(inputPolygon1, inputPolygon2))
return true
}
R.id.action_symmetric_difference -> {
showGeometry(GeometryEngine.symmetricDifference(inputPolygon1, inputPolygon2))
return true
}
else -> {
return super.onOptionsItemSelected(item)
}
}
}

override fun onResume() {
super.onResume()
mapView.resume()
}

override fun onPause() {
mapView.pause()
super.onPause()
}

override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}``````