Примеры | RasterJS API | 2GIS Documentation
RasterJS API

Базовое использование

Ниже приведены примеры базового использования карты. Для получения подробной информации о работе с картой воспользуйтесь разделами документации Подключение API и Карта.

<!DOCTYPE html>
<html>

<head>
    <title>Создание карты</title>
    <script src="https://maps.api.2gis.ru/2.0/loader.js"></script>
    <style>
        html,
        body,
        #map {
            height: 100%;
            margin: 0;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        DG.then(function () {
            DG.map('map', {
                center: [54.98, 82.89],
                zoom: 13
            });
        });
    </script>
</body>

</html>

Инициализация карты по требованию (удобно при отображении карты во всплывающем окне):

<!DOCTYPE html>
<html>

<head>
    <title>Создание карты по требованию</title>
    <script src="https://maps.api.2gis.ru/2.0/loader.js?lazy=true"></script>
    <style>
        html,
        body,
        #mapBlock,
        #map {
            height: 100%;
            margin: 0;
        }
    </style>
</head>

<body>
    <input id="create" type="button" value="Показать карту" />
    <div id="mapBlock"></div>
    <script>
        var createButton = document.getElementById('create');
        createButton.onclick = function () {
            var container = document.createElement('div'),
                mapBlock = document.getElementById('mapBlock');
            container.id = 'map';
            mapBlock.appendChild(container);
            createButton.style.display = 'none';
            DG.then(function () {
                DG.map('map', {
                    center: [54.98, 82.89],
                    zoom: 13
                });
            });
        }
    </script>
</body>

</html>

Ниже представлен пример вызова карты с таким набором опций: pkg=basic, skin=light. Как результат мы получим сборку с базовой функциональностью в светлой теме. Все возможные опции можно посмотреть в разделе Опции подключения.

<!DOCTYPE html>
<html>

<head>
    <title>Use of connection options</title>
    <script src="https://maps.api.2gis.ru/2.0/loader.js?pkg=basic&skin=light"></script>
    <style>
        html,
        body,
        #map {
            height: 100%;
            margin: 0;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        DG.then(function () {
            DG.map('map', {
                center: [54.98, 82.89],
                zoom: 13
            });
        });
    </script>
</body>

</html>

При клике на кнопку изменяется размер контейнера и карта подстраивается под новый размер:

<!DOCTYPE html>
<html>

<head>
    <title>Изменение размера карты</title>
    <script src="https://maps.api.2gis.ru/2.0/loader.js"></script>
    <style>
        html,
        body,
        #map {
            height: 100%;
            margin: 0;
        }

        #changeSize {
            position: absolute;
            top: 5px;
            left: 70px;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <input id="changeSize" type="button" value="Изменить размер" />
    <script>
        var changeSizeButton = document.getElementById('changeSize');
        DG.then(function () {
            var map,
                enabled = false;
            map = DG.map('map', {
                center: [54.98, 82.89],
                zoom: 15,
                animate: true
            });
            changeSizeButton.onclick = function () {
                enabled = !enabled;
                var mapDiv = document.getElementById('map');
                mapDiv.style.width = (enabled ? '50' : '100') + '%';
                // обновление карты
                map.invalidateSize();
            }
        });
    </script>
</body>

</html>

Пример отображения статической карты:

<!DOCTYPE html>
<html>

<head>
    <title>Отключение опций взаимодействия</title>
    <script src="https://maps.api.2gis.ru/2.0/loader.js"></script>
    <style>
        html,
        body,
        #map {
            height: 100%;
            margin: 0;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        DG.then(function () {
            DG.map('map', {
                center: [54.98, 82.89],
                zoom: 13,
                dragging: false,
                touchZoom: false,
                scrollWheelZoom: false,
                doubleClickZoom: false,
                boxZoom: false,
                geoclicker: false,
                zoomControl: false,
                fullscreenControl: false
            });
        });
    </script>
</body>

</html>

Пример определения географического расположения пользователя:

<!DOCTYPE html>
<html>

<head>
    <title>Определение местоположения пользователя</title>
    <script src="https://maps.api.2gis.ru/2.0/loader.js"></script>
    <style>
        html,
        body,
        #map {
            height: 100%;
            margin: 0;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        DG.then(function () {
            var map;
            map = DG.map('map', {
                center: [54.98, 82.89],
                zoom: 13
            });
            map.locate({ setView: true, watch: true })
                .on('locationfound', function (e) {
                    DG.marker([e.latitude, e.longitude]).addTo(map);
                })
                .on('locationerror', function (e) {
                    DG.popup()
                        .setLatLng(map.getCenter())
                        .setContent('Доступ к определению местоположения отключён')
                        .openOn(map);
                });
        });
    </script>
</body>

</html>