---
metadata:
  - name: generator
    content: Diplodoc Platform v5.39.1
alternate:
  - https://yandex.ru/dev/maps/archive/doc/jsapi/2-0/ru/examples/cases/geolocation.md
---
# Создание карты с местоположением пользователя

<iframe id="LIVE-EXAMPLE" style="width:100%;height: 400px;border-radius: 8px;border: 1px solid rgba(92, 94, 102, 0.14);" frameBorder="0" src="https://yastatic.net/s3/front-maps-static/maps-front-jsapi-v2-0/examples/1/out/s3-cases/ru/geolocation/index.html" allow="fullscreen"></iframe>

<a target="_blank" rel="noopener noreferrer" style="display: inline-block;margin-top: 10px;cursor: pointer;border-radius: 4px;padding: 9px 12px;background: #151515;color: white;text-decoration: none;font-weight: 500" href="https://codesandbox.io/p/sandbox/7d239d?file=index.html">Open in CodeSandbox</a>

<div id="doc">
<div id="references">
    <a href="http://www.w3.org/TR/geolocation-API/">Geolocation API</a>, <a href="https://yandex.ru/dev/maps/archive/doc/jsapi/2-0/ru/ref/reference/geocode">geocode</a>,
    <a href="https://yandex.ru/dev/maps/archive/doc/jsapi/2-0/ru/ref/reference/geolocation">ymaps.geolocation</a>
</div>
<p>
  Данный пример демонстрирует, как создать карту, изначально отцентрированную по местоположению пользователя.</p>
<p>
  В примере используется класс GeolocationService, который определяет местоположение пользовтаеля с помощью <a href="http://www.w3.org/TR/geolocation-API/">Geolocation API</a>.
  Если сервис не поддерживается браузером, или при определении местоположения возникает ошибка, то используется <a href="https://yandex.ru/dev/maps/archive/doc/jsapi/2-0/ru/ref/reference/geolocation">ymaps.geolocation</a> (по IP).
</p>
</div>

{% list tabs %}

-   index.html

    ```html
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>
                Примеры. Создание карты с местоположением пользователя.
            </title>
            <meta
                http-equiv="Content-Type"
                content="text/html; charset=utf-8"
            />
            <link
                href="https://yandex.st/bootstrap/3.0.0/css/bootstrap.min.css"
                rel="stylesheet"
            />
            
            <!--
            Укажите свой API-ключ. Тестовый ключ НЕ БУДЕТ работать на других сайтах.
            Получить ключ можно в Кабинете разработчика: https://developer.tech.yandex.ru/keys/
        -->
            
            
            

            
        </head>
        <body>
            <div class="hero-unit">
                <div class="container">
                    <div id="YMapsID"></div>
                </div>
            </div>
        </body>
    </html>
    ```

-   geolocation_service.js

    ```js
    /**
     * Класс сервиса геолокации.
     * Определяет местоположение с использованием Geolocation API браузера.
     * В случае его отсутствия или ошибки определяет местоположение по IP с помощью API Яндекс.Карт.
     * @see http://www.w3.org/TR/geolocation-API/
     * @see http://api.yandex.ru/maps/doc/jsapi/2.x/ref/reference/geolocation.xml
     * @class
     * @name GeolocationService
     */
    function GeolocationService() {
        this._location = new ymaps.util.Promise();
    }

    /**
     * @lends GeolocationService.prototype
     */
    GeolocationService.prototype = {
        /**
         * @constructor
         */
        constructor: GeolocationService,
        /**
         * Определяем местоположение пользователя всеми доступными средствами.
         * @function
         * @name GeolocationService.getLocation
         * @params {Object} [options] Опции GeolocationAPI
         * @see http://www.w3.org/TR/geolocation-API/#position-options
         * @returns {ymaps.util.Promise} Возвращает объект-обещание.
         */
        getLocation: function (options) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    ymaps.util.bind(this._onGeolocationSuccess, this),
                    ymaps.util.bind(this._onGeolocationError, this),
                    options
                );
            } else {
                this._location.resolve(
                    this.getLocationByIP() || this.getDefaults()
                );
            }

            return this._sync();
        },
        /**
         * Обертка над оригинальным промисом, чтобы его нельзя было зареджектить
         * из пользовательского кода.
         * @private
         * @function
         * @name GeolocationService._sync
         * @returns {ymaps.util.Promise} Промис-обертка.
         */
        _sync: function (p) {
            var promise = new ymaps.util.Promise();

            this._location.then(
                function (res) {
                    promise.resolve(res);
                },
                function (err) {
                    promise.reject(err);
                }
            );

            return promise;
        },
        /**
         * Перегружаем промис для обновления местоположения при повторных вызовах getLocation.
         * @private
         * @function
         * @name GeolocationService._reset
         */
        _reset: function () {
            this._location = new ymaps.util.Promise();
        },
        /**
         * Обработчик результата геолокации.
         * @private
         * @function
         * @name GeolocationService._onGeolocationSuccess
         * @param {Object} position Объект с описанием местоположения.
         * @see http://www.w3.org/TR/geolocation-API/#position_interface
         */
        _onGeolocationSuccess: function (position) {
            this._location.resolve(position.coords);

            this._reset();
        },
        /**
         * Обработчик ошибки геолокации.
         * @private
         * @function
         * @name GeolocationService._onGeolocationError
         * @param {Object|Number} error Объект или код ошибки.
         * @see http://www.w3.org/TR/geolocation-API/#position_error_interface
         */
        _onGeolocationError: function (error) {
            // Выводим в консоль описание ошибки.
            if (window.console) {
                console.log(
                    error.message ||
                        this.constructor.GEOLOCATION_ERRORS[error + 1]
                );
            }

            this._location.resolve(
                this.getLocationByIP() || this.getDefaults()
            );

            this._reset();
        },
        /**
         * Возвращает данные о местоположении пользователя на основе его IP-адреса.
         * @see http://api.yandex.ru/maps/doc/jsapi/2.x/ref/reference/geolocation.xml
         * @function
         * @name GeolocationService.getLocationByIP
         * @returns {Object|null} Местоположение пользователя.
         */
        getLocationByIP: function () {
            return ymaps.geolocation;
        },
        /**
         * Возвращает местоположение по умолчанию.
         * Удобно для перекрытия.
         * @function
         * @name GeolocationService.getDefaults
         * @returns {Object} Местоположение пользователя.
         */
        getDefaults: function () {
            // По умолчанию возвращаем Москву.
            return {
                latitude: 55.751574,
                longitude: 37.573856,
                zoom: 9,
            };
        },
    };

    /**
     * Человекопонятное описание кодов ошибок Geolocation API.
     * @see http://www.w3.org/TR/geolocation-API/#position_error_interface
     * @static
     */
    GeolocationService.GEOLOCATION_ERRORS = [
        "permission denied",
        "position unavailable",
        "timeout",
    ];
    ```

-   geolocation.js

    ```js
    ymaps.ready(function () {
        var myMap,
            service = new GeolocationService(),
            myLocation = service.getLocation({
                // Режим получения наиболее точных данных.
                enableHighAccuracy: true,
                // Максимальное время ожидания ответа (в миллисекундах).
                timeout: 10000,
                // Максимальное время жизни полученных данных (в миллисекундах).
                maximumAge: 1000,
            });

        myLocation.then(function (loc) {
            var myCoords = [loc.latitude, loc.longitude],
                myPlacemark = new ymaps.Placemark(
                    myCoords,
                    {},
                    {
                        iconImageHref: "pin.svg",
                        iconImageSize: [24, 24],
                        iconImageOffset: [-12, -12],
                    }
                );

            myMap = new ymaps.Map("YMapsID", {
                center: myCoords,
                zoom: loc.zoom || 9,
                behaviors: ["default", "scrollZoom"],
            });

            myMap.geoObjects.add(myPlacemark);
        });
    });
    ```

{% endlist %}
