Масштабирование по границам | MapGL | 2GIS Documentation
MapGL JS API

Масштабирование по границам

Чтобы уместить все нужные объекты на карте, можно вызвать метод fitBounds(), который автоматически изменит центр и масштаб карты в соответствии с указанными границами. Метод принимает два параметра: координаты северо-восточной точки (правый верхний угол карты) и координаты юго-западной точки (левый нижний угол карты).

map.fitBounds({
    northEast: [82.927622, 55.033432],
    southWest: [82.921622, 55.027432],
});
<!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="Example of a fitBounds" />
        <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 zoom = 16;
            const rotation = 45;
            const center = [55.26553, 25.23399];

            const map = new mapgl.Map('container', {
                key: 'Your API access key',
                disableZoomOnScroll: true,
                rotation,
                center,
                zoom,
            });

            const s = 0.0005;
            const x = center[0];
            const y = center[1];
            const bound = [
                [x-s, y-s],
                [x+s, y-s],
                [x+s, y+s],
                [x-s, y+s],
            ];
            new mapgl.Polygon(map, { coordinates: [[...bound, bound[0]]] });

            const control = new mapgl.Control(map, '<button>Fit bounds</button>', {
                position: 'topLeft',
            });
            control
                .getContainer() // Get a control's wrap
                .querySelector('button') // Get an inner button HTML element reference
                .addEventListener('click', () => {
                    map.fitBounds({
                        northEast: bound[2],
                        southWest: bound[0],
                    });
                });

            const reset = new mapgl.Control(map, '<button>Reset</button>', {
                position: 'topLeft',
            });
            reset
                .getContainer()
                .querySelector('button')
                .addEventListener('click', () => {
                    map
                        .setZoom(zoom)
                        .setCenter(center)
                        .setRotation(rotation)
                })
        </script>
    </body>
</html>

Если для карты были указаны отступы (padding), они будут учтены при масштабировании. Чтобы не учитывать отступы, нужно указать параметр skipMapPadding.

map.fitBounds(
    {
        northEast: [82.927622, 55.033432],
        southWest: [82.921622, 55.027432],
    },
    {
        skipMapPadding: true,
    },
);

Также при масштабировании можно указать дополнительные отступы с помощью параметра padding. Эти отступы будут добавлены к отступам, указанным для карты.

map.fitBounds(
    {
        northEast: [82.927622, 55.033432],
        southWest: [82.921622, 55.027432],
    },
    {
        padding: { top: 20, left: 60, bottom: 20, right: 60 },
    },
);
<!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="Example of a fitBounds" />
        <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 zoom = 16;
            const rotation = 45;
            const center = [55.26553, 25.23399];

            const map = new mapgl.Map('container', {
                key: 'Your API access key',
                disableZoomOnScroll: true,
                rotation,
                center,
                zoom,
                padding: { top: 20, left: 60, bottom: 20, right: 60 }
            });

            const s = 0.0005;
            const x = center[0];
            const y = center[1];
            const bound = [
                [x-s, y-s],
                [x+s, y-s],
                [x+s, y+s],
                [x-s, y+s],
            ];
            new mapgl.Polygon(map, { coordinates: [[...bound, bound[0]]] });

            const control = new mapgl.Control(map, '<button>Fit bounds</button>', {
                position: 'topLeft',
            });
            control
                .getContainer() // Get a control's wrap
                .querySelector('button') // Get an inner button HTML element reference
                .addEventListener('click', (ev) => {
                    map.fitBounds({
                        northEast: bound[2],
                        southWest: bound[0],
                    }, {
                        padding: { top: 20, left: 60, bottom: 20, right: 60 }
                    });
                });

            const reset = new mapgl.Control(map, '<button>Reset</button>', {
                position: 'topLeft',
            });
            reset
                .getContainer()
                .querySelector('button')
                .addEventListener('click', () => {
                    map
                        .setZoom(zoom)
                        .setCenter(center)
                        .setRotation(rotation)
                })
        </script>
    </body>
</html>

Чтобы сохранить угол поворота карты при масштабировании, нужно указать параметр considerRotation.

map.fitBounds(
    {
        northEast: [82.927622, 55.033432],
        southWest: [82.921622, 55.027432],
    },
    {
        considerRotation: true,
    },
);
<!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="Example of a fitBounds" />
        <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 zoom = 16;
            const rotation = 45;
            const center = [55.26553, 25.23399];

            const map = new mapgl.Map('container', {
                key: 'Your API access key',
                disableZoomOnScroll: true,
                rotation,
                center,
                zoom,
            });

            const s = 0.0005;
            const x = center[0];
            const y = center[1];
            const bound = [
                [x-s, y-s],
                [x+s, y-s],
                [x+s, y+s],
                [x-s, y+s],
            ];
            new mapgl.Polygon(map, { coordinates: [[...bound, bound[0]]] });

            const control = new mapgl.Control(map, '<button>Fit bounds</button>', {
                position: 'topLeft',
            });
            control
                .getContainer() // Get a control's wrap
                .querySelector('button') // Get an inner button HTML element reference
                .addEventListener('click', (ev) => {
                    map.fitBounds({
                        northEast: bound[2],
                        southWest: bound[0],
                    }, {
                        considerRotation: true,
                    });
                });

            const reset = new mapgl.Control(map, '<button>Reset</button>', {
                position: 'topLeft',
            });
            reset
                .getContainer()
                .querySelector('button')
                .addEventListener('click', () => {
                    map
                        .setZoom(zoom)
                        .setCenter(center)
                        .setRotation(rotation)
                })
        </script>
    </body>
</html>