Project a point from one spatial reference to another.

Use case
Being able to project between spatial references is fundamental to a GIS. An example of when you would need to re-project data is if you had data in two different spatial references, but wanted to perform an intersect analysis with the GeometryEngine.intersect function. This function takes two geometries as parameters, and both geometries must be in the same spatial reference. If they are not, you could first use GeometryEngine.project to convert the geometries so they match.
How to use the sample
Click anywhere on the map. A Textview will display the clicked location’s coordinate in the original (basemap’s) spatial reference and in the projected spatial reference.
How it works
- Call the static method,
GeometryEngine.project, passing in the originalGeometryand aSpatialReferenceto which it should be projected.
Relevant API
- GeometryEngine
- Point
- SpatialReference
Additional information
In cases where the the output spatial reference uses a different geographic coordinate system than that of the input spatial reference, see the GeometryEngine.project method that additionally takes in a DatumTransformation parameter.
This sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.
Tags
coordinate system, coordinates, geoview-compose, latitude, longitude, projected, projection, spatial reference, toolkit, Web Mercator, WGS 84
Sample Code
/* Copyright 2024 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.projectgeometry
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.projectgeometry.screens.ProjectGeometryScreen
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 { ProjectGeometryApp() } } }
@Composable private fun ProjectGeometryApp() { Surface(color = MaterialTheme.colorScheme.background) { ProjectGeometryScreen( sampleName = getString(R.string.project_geometry_app_name) ) } }}/* Copyright 2024 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.projectgeometry.components
import android.app.Applicationimport android.graphics.BitmapFactoryimport android.graphics.drawable.BitmapDrawableimport androidx.core.graphics.drawable.toDrawableimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.geometry.GeometryEngineimport com.arcgismaps.geometry.Pointimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.symbology.PictureMarkerSymbolimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.mapping.view.SingleTapConfirmedEventimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.esri.arcgismaps.sample.projectgeometry.Rimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launch
class ProjectGeometryViewModel(app: Application) : AndroidViewModel(app) { // create a map with a navigation night basemap style val arcGISMap = ArcGISMap(BasemapStyle.ArcGISStreetsNight).apply { // set the default viewpoint to Redlands,CA initialViewpoint = Viewpoint( latitude = 34.058, longitude = -117.195, scale = 5e4 ) } // create a MapViewProxy to interact with the MapView val mapViewProxy = MapViewProxy()
// Create a message dialog view model for handling error messages val messageDialogVM = MessageDialogViewModel()
// state flow of a point and its projection for presentation in UI private val _pointProjectionFlow = MutableStateFlow<PointProjection?>(null) val pointProjectionFlow = _pointProjectionFlow.asStateFlow()
// setup the red pin marker image as bitmap drawable private val markerDrawable: BitmapDrawable by lazy { // load the bitmap from resources and create a drawable val bitmap = BitmapFactory.decodeResource(app.resources, R.drawable.pin_symbol) bitmap.toDrawable(app.resources) }
// setup the red pin marker as a Graphic private val markerGraphic: Graphic by lazy { // creates a symbol from the marker drawable val markerSymbol = PictureMarkerSymbol.createWithImage(markerDrawable).apply { // resize the symbol into a smaller size width = 30f height = 30f // offset in +y axis so the marker spawned is right on the touch point offsetY = 25f } // create the graphic from the symbol Graphic(symbol = markerSymbol) }
val graphicsOverlay = GraphicsOverlay().apply { graphics.add(markerGraphic) }
init { viewModelScope.launch { arcGISMap.load().onFailure { error -> messageDialogVM.showMessageDialog( title = "Failed to load map", description = error.message.toString() ) } } }
fun onMapViewTapped(event: SingleTapConfirmedEvent) { event.mapPoint?.let { point -> // update the marker location to where the user tapped on the map markerGraphic.geometry = point // set mapview to recenter to the tapped location viewModelScope.launch { // set mapview to recenter to the tapped location mapViewProxy.setViewpointCenter(point) } // project the point from web mercator to WGS84 val projectedPoint = GeometryEngine.projectOrNull( geometry = point, spatialReference = SpatialReference.wgs84() ) projectedPoint?.let { projection -> _pointProjectionFlow.value = PointProjection(point, projection) } ?: messageDialogVM.showMessageDialog( title = "Error", description = "Couldn't project point." ) } }}
/** * Data class representing a point and its projection into another spatial reference. */data class PointProjection (val original: Point, val projection: Point)/* Copyright 2024 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.projectgeometry.screens
import 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.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dpimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.geometry.Pointimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.projectgeometry.Rimport com.esri.arcgismaps.sample.projectgeometry.components.ProjectGeometryViewModelimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBarimport java.util.Locale
/** * Main screen layout for the sample app */@Composablefun ProjectGeometryScreen(sampleName: String) { val mapViewModel: ProjectGeometryViewModel = viewModel() val pointProjectionInfo by mapViewModel.pointProjectionFlow.collectAsStateWithLifecycle()
val infoText = pointProjectionInfo?.let { (original, projection) -> stringResource( R.string.projection_info_text, original.toDisplayFormat(), projection.toDisplayFormat() ) } ?: ""
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, content = { Column( modifier = Modifier .fillMaxSize() .padding(it), ) { MapView( modifier = Modifier .fillMaxSize() .weight(1f), arcGISMap = mapViewModel.arcGISMap, mapViewProxy = mapViewModel.mapViewProxy, graphicsOverlays = listOf(mapViewModel.graphicsOverlay), onSingleTapConfirmed = mapViewModel::onMapViewTapped )
Row( modifier = Modifier .padding(12.dp) .fillMaxWidth() ) { Column { Text( text = pointProjectionInfo?.let { stringResource(R.string.title_text) } ?: stringResource(R.string.tap_to_begin), fontWeight = FontWeight.Bold ) Text( text = infoText, minLines = 2 ) } }
}
mapViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } } )}
/** * Extension function for the Point type that returns * a float-precision formatted string suitable for display */private fun Point.toDisplayFormat() = "${String.format(Locale.getDefault(),"%.5f", x)}, ${String.format(Locale.getDefault(),"%.5f", y)}"