Выделение объектов | MapGL | 2GIS Documentation

Object selection

You can select objects on the map, such as buildings, roads and others.

For selection you need to get a unique identifier of an object through a mouse and touch events handling. See the target property of the MapPointerEvent.

To select an object, pass its identifier to the setSelectedObjects method:

map.setSelectedObjects([id]);

To select more objects, pass an array of their identifiers:

map.setSelectedObjects([id1, id2]);

To unselect all objects, call this method with no arguments:

map.setSelectedObjects();

For example, a selection of objects by click on the map layer. To unselect an object, click on it again.

let selectedIds = [];

map.on('click', (e) => {
    if (!e.target) {
        return;
    }

    const { id } = e.target;

    if (selectedIds.includes(id)) {
        selectedIds = selectedIds.filter((i) => i !== id);
    } else {
        selectedIds.push(id);
    }

    map.setSelectedObjects(selectedIds);
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="An object selection example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.308, 25.237],
                zoom: 18,
                key: 'Your API access key',
            });

            let selectedIds = [];

            map.on('click', (e) => {
                if (!e.target) {
                    return;
                }

                const { id } = e.target;

                if (selectedIds.includes(id)) {
                    selectedIds = selectedIds.filter((i) => i !== id);
                } else {
                    selectedIds.push(id);
                }

                map.setSelectedObjects(selectedIds);
            });
        </script>
    </body>
</html>