Select to view content in your preferred language

Kotlin Data Collection Application

747
3
10-28-2023 03:38 AM
HarishKV
Regular Contributor

Hi Community,

 

I am trying to develop a Kotlin android application using ArcGIS Maps SDK Kotlin and ArcGIS Runtime 200. The data collection I want to apply for a polygon layer. I had gone through some of the sample projects which is talking about data collection on a point Layer. My question here is to implement the polygon editin g which classes i have to use. Is it com.esri.arcgismaps.geometry.Polygon and addFeature function OR use the Sketch Editor.

Tags (3)
0 Kudos
3 Replies
RamaChintapalli
Esri Contributor

Hi,

For sketching (including polygon) you can use the GeometryEditor. Here is a sample that show cases the sketching experience. The result geometry from the sketching can then be applied to your feature table edits.

Thanks
Rama

HarishKV
Regular Contributor

Hi Rama,

 

I had written the code like follows and has some errors in the applyEdits can you check and comment on the same "

package com.esri.arcgismaps.sample.sketchonmap

import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.Color
import com.arcgismaps.data.ServiceFeatureTable
import com.arcgismaps.geometry.GeometryBuilder
import com.arcgismaps.geometry.GeometryType
import com.arcgismaps.geometry.Multipoint
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.Polygon
import com.arcgismaps.geometry.Polyline
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.symbology.SimpleFillSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbol
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbolStyle
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditor
import com.arcgismaps.mapping.view.geometryeditor.VertexTool
import com.arcgismaps.mapping.layers.FeatureLayer
import com.arcgismaps.mapping.view.LocationDisplay
import com.esri.arcgismaps.sample.sketchonmap.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import android.Manifest
import android.widget.Toast

class MainActivity : AppCompatActivity() {

private val activityMainBinding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_main)
}

private val mapView by lazy {
activityMainBinding.mapView
}

private val selectedGeometryDropdown by lazy {
activityMainBinding.pointLinePolygonToolbar.selectGeometryDropdown
}

private val locationDisplay: LocationDisplay by lazy {
mapView.locationDisplay
}

// create a symbol for the point graphic
private val pointSymbol: SimpleMarkerSymbol by lazy {
SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square,
Color(getColor(R.color.point_symbol_color)),
20f)
}

// create a symbol for a line graphic
private val lineSymbol: SimpleLineSymbol by lazy {
SimpleLineSymbol(
SimpleLineSymbolStyle.Solid,
Color(getColor(R.color.line_symbol_color)),
4f
)
}

// create a symbol for the fill graphic
private val fillSymbol: SimpleFillSymbol by lazy {
SimpleFillSymbol(
SimpleFillSymbolStyle.Cross,
Color(getColor(R.color.fill_symbol_color)),
lineSymbol
)
}

// keep the instance graphic overlay to add graphics on the map
private var graphicsOverlay: GraphicsOverlay = GraphicsOverlay()

// keep the instance of the vertex tool
private val vertexTool: VertexTool = VertexTool()

// keep the instance to create new geometries, and change existing geometries
private var geometryEditor: GeometryEditor = GeometryEditor()

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.API_KEY)
lifecycle.addObserver(mapView)

// create and add a map with a navigation night basemap style
mapView.apply {
map = ArcGISMap(BasemapStyle.ArcGISLightGray)
setViewpoint(Viewpoint(34.056295, -117.195800, 100000.0))
graphicsOverlays.add(graphicsOverlay)
val landUrl = "https://services7.arcgis.com/r3Nggl3TgKPtY1CE/arcgis/rest/services/Plot_area/FeatureServer"
val landServiceFeatureTable = ServiceFeatureTable(landUrl)
map!!.operationalLayers.add(FeatureLayer.createWithFeatureTable(landServiceFeatureTable))

}

// set MapView's geometry editor to sketch on map
mapView.geometryEditor = geometryEditor

// enable/disable the undo button if last event can be undone
lifecycleScope.launch {
geometryEditor.canUndo.collect { value ->
activityMainBinding.pointLinePolygonToolbar.undoButton.isEnabled = value
}
}

// enable/disable the redo button if the last event can be redone
lifecycleScope.launch {
geometryEditor.canRedo.collect { value ->
activityMainBinding.pointLinePolygonToolbar.redoButton.isEnabled = value
}
}

// set up the geometry list dropdown
selectedGeometryDropdown.apply {
// set the adapter to the list of geometries
setAdapter(
ArrayAdapter(
applicationContext,
com.esri.arcgismaps.sample.sampleslib.R.layout.custom_dropdown_item,
resources.getStringArray(R.array.geometry_list)
)
)

// set the dropdown click listener
onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
// set the GeometryEditorTool and then start the editing process
geometryEditor.apply {
when (position) {
0 -> {
tool = vertexTool
start(GeometryType.Polygon)
}

}
}
}
}
}

/**
* Undo the last event on the GeometryEditor.
*/
fun undo(view: View) {
geometryEditor.undo()
}

/**
* Redo the last undone event on the GeometryEditor.
*/
fun redo(view: View) {
geometryEditor.redo()
}

private fun requestPermissions() {
// coarse location permission
val permissionCheckCoarseLocation =
ContextCompat.checkSelfPermission(
this@MainActivity,
Manifest.permission.ACCESS_COARSE_LOCATION
) ==
PackageManager.PERMISSION_GRANTED
// fine location permission
val permissionCheckFineLocation =
ContextCompat.checkSelfPermission(
this@MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION
) ==
PackageManager.PERMISSION_GRANTED

// if permissions are not already granted, request permission from the user
if (!(permissionCheckCoarseLocation && permissionCheckFineLocation)) {
ActivityCompat.requestPermissions(
this@MainActivity,
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
),
2
)
} else {
// permission already granted, so start the location display
lifecycleScope.launch {
locationDisplay.dataSource.start()
}
}
}

override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// if request is cancelled, the results array is empty
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
lifecycleScope.launch {
locationDisplay.dataSource.start()
}
}

}

private fun showError(message: String) {
Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()
Log.e(localClassName, message)
}

/**
* When the stop button is clicked, check that sketch is valid. If so, get the geometry from
* the sketch, set its symbol and add it to the graphics overlay.
*/
fun stop(view: View) {
// get the geometry from sketch editor
val sketchGeometry = geometryEditor.geometry.value
?: return showMessage("Error retrieving geometry")

if (!GeometryBuilder.builder(sketchGeometry).isSketchValid) {
return reportNotValid()
}

// stops the editing session
geometryEditor.stop()

// clear the UI selection
selectedGeometryDropdown.setText("")
selectedGeometryDropdown.clearFocus()

// create a graphic from the sketch editor geometry
val graphic = Graphic(sketchGeometry).apply {
// assign a symbol based on geometry type
symbol = when (sketchGeometry) {
is Polygon -> fillSymbol
is Polyline -> lineSymbol
is Point, is Multipoint -> pointSymbol
else -> null
}
}

// add the graphic to the graphics overlay
graphicsOverlay.graphics.add(graphic)

applyEditsToServiceFeatureTable(graphic)
}

private fun applyEditsToServiceFeatureTable(graphic: Graphic) {

val landUrl = "https://services7.arcgis.com/r3Nggl3TgKPtY1CE/arcgis/rest/services/Plot_area/FeatureServer"
val landServiceFeatureTable = ServiceFeatureTable(landUrl)

// Create a feature with the geometry from the graphic
val feature = landServiceFeatureTable.createFeature(graphic.geometry as com.arcgismaps.geometry.Geometry)

// Add the feature to the list of features to be updated
val featuresToUpdate = mutableListOf(feature)

// Apply edits to the service feature table
landServiceFeatureTable.applyEditsAsync(featuresToUpdate, null, null) { result ->
if (result.isSuccessful) {
showMessage("Edits applied successfully")
} else {
showMessage("Error applying edits: ${result.error.message}")
}
}

}

/**
* Clear the MapView of all the graphics and reset selections
*/
fun clear(view: View) {
geometryEditor.clearGeometry()
geometryEditor.clearSelection()
geometryEditor.stop()
selectedGeometryDropdown.setText("")
selectedGeometryDropdown.clearFocus()
showMessage(getString(R.string.cleared_message))
}

/**
* Clear all editing and applied graphics on the map
*/
fun restart(view: View) {
graphicsOverlay.graphics.clear()
geometryEditor.clearGeometry()
geometryEditor.clearSelection()
geometryEditor.stop()
selectedGeometryDropdown.setText("")
selectedGeometryDropdown.clearFocus()
showMessage(getString(R.string.restart_message))
}

/**
* Called if sketch is invalid. Reports to user why the sketch was invalid.
*/
private fun reportNotValid() {
// get the geometry currently being added to map
val geometry = geometryEditor.geometry.value ?: return showMessage("Geometry not found")
// find the geometry type, and set the valid message
val validIfText: String = when (geometry) {
is Point -> getString(R.string.invalid_point_message)
is Multipoint -> getString(R.string.invalid_multipoint_message)
is Polyline -> getString(R.string.invalid_polyline_message)
is Polygon -> getString(R.string.invalid_polygon_message)
else -> getString(R.string.none_selected_message)
}
// set the invalid message to the TextView.
showMessage(validIfText)
}

private fun showMessage(message: String) {
Log.e(localClassName, message)
Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show()
}
}

"

0 Kudos
HarishKV
Regular Contributor

@RamaChintapalli expecting you reply

0 Kudos