Skip to main content

Coordinate where a selection event happened

UPDATED: | POSTED: | by Markus Holler

In this article, we will demonstrate how you can get the click position when an element was selected in the map. This can for example be used to use the coordinate of the click to execute a query on the server.

In RIA, you can easily listen to the map selection like following:


window.map.on('SelectionChanged', event => {
    ...
    }
});

Unfortunately, the event will not share the information about where the click on the element has happened. For that, the M.App Enterprise API added an additional function to retrieve the coordinate of the click:


var coordinates: Map = window.map.stores.mapState.selectedObjectsSurfacePointMap;

We can now apply this to an example. Let's assume that you want to use the click position to execute a spatial query to find related objects within 200 meters. This should only happen, when the click is done on a specific layer.


window.map.on('SelectionChanged', event => {
    if (window?.map?.selectedObjects?.[0]?.selected?.[0]?.id && window.map.selectedObjects[0].layer.label == "My Layer Name") {
        // get the id of the first selected element
        var id = window.map.selectedObjects[0].selected[0].id;
        
        // get the coordinates of the click position for the selected object
        var coordinates: Map = window.map.stores.mapState.selectedObjectsSurfacePointMap;
        var clickPosition = coordinates.get(id.toString());
        if(clickPosition == null)
            return;

        // convert the coordinate into the coordinate system used in the DB
        const coordinateSystem = ReferenceProvider.getReference('EPSG:31255');
        const transformation = TransformationFactory.createTransformation(clickPosition.reference, coordinateSystem);
        
        // execute the query with the coordinate
        executeQuery(transformation.transform(clickPosition));
    }
});

In the case you are eager to learn more about how to execute a query from a browser app, please take a look on the following article:

Query execution for Browser Apps
Running queries in a Browser application requires appropriate adjustments in the M.App Editor. You will have several options to retrieve dataset information through a query, which will be detailed in this tutorial. The real magic happens in the M.App Editor, where you can access and seamlessly integrate a