---
metadata:
  - name: generator
    content: Diplodoc Platform v5.39.1
alternate:
  - https://yandex.com.tr/dev/jsapi-v2-1/doc/en/v2-1/examples/cases/custom_control.md
  - https://yandex.com.tr/dev/jsapi-v2-1/doc/ru/v2-1/examples/cases/custom_control.md
---
> **Documentation Index:** Fetch the complete configuration index at https://yandex.com.tr/dev/jsapi-v2-1/doc/ru/llms.txt

# Собственный элемент управления

<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-1/examples/2/out/s3-cases/ru/custom_control/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/dnnpdm?file=index.html">Open in CodeSandbox</a>

<div id="references">
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/ready">ready</a>,
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/Map">Map</a>,
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/collection.Item">collection.Item</a>,
    <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/IControl-docpage/">IControl</a>
</div>
<p>
    В примере показано, как создавать собственные элементы управления. Класс элемента управления
    должен реализовывать интерфейс <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/IControl-docpage/">IControl</a>.
</p>
<p>
    Для ускорения разработки, можно отнаследовать класс элемента управления от класса <a href="https://yandex.ru/dev/jsapi-v2-1/doc/ru/v2-1/ref/reference/collection.Item">collection.Item</a>.
</p>

{% 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"
            />
            <!--
            Укажите свой API-ключ. Тестовый ключ НЕ БУДЕТ работать на других сайтах.
            Получить ключ можно в Кабинете разработчика: https://developer.tech.yandex.ru/keys/
        -->
            
            
            
            
        </head>
        <body>
            <div id="map"></div>
        </body>
    </html>
    ```

-   custom_control.js

    ```js
    ymaps.ready(function () {
        // Пример реализации собственного элемента управления на основе наследования от collection.Item.
        // Элемент управления отображает название объекта, который находится в центре карты.
        var map = new ymaps.Map("map", {
                center: [55.819543, 37.611619],
                zoom: 6,
                controls: [],
            }),
            // Создаем собственный класс.
            CustomControlClass = function (options) {
                CustomControlClass.superclass.constructor.call(this, options);
                this._$content = null;
                this._geocoderDeferred = null;
            };
        // И наследуем его от collection.Item.
        ymaps.util.augment(CustomControlClass, ymaps.collection.Item, {
            onAddToMap: function (map) {
                CustomControlClass.superclass.onAddToMap.call(this, map);
                this._lastCenter = null;
                this.getParent()
                    .getChildElement(this)
                    .then(this._onGetChildElement, this);
            },

            onRemoveFromMap: function (oldMap) {
                this._lastCenter = null;
                if (this._$content) {
                    this._$content.remove();
                    this._mapEventGroup.removeAll();
                }
                CustomControlClass.superclass.onRemoveFromMap.call(
                    this,
                    oldMap
                );
            },

            _onGetChildElement: function (parentDomContainer) {
                // Создаем HTML-элемент с текстом.
                this._$content = $(
                    '<div class="customControl"></div>'
                ).appendTo(parentDomContainer);
                this._mapEventGroup = this.getMap().events.group();
                // Запрашиваем данные после изменения положения карты.
                this._mapEventGroup.add(
                    "boundschange",
                    this._createRequest,
                    this
                );
                // Сразу же запрашиваем название места.
                this._createRequest();
            },

            _createRequest: function () {
                var lastCenter = (this._lastCenter = this.getMap()
                    .getCenter()
                    .join(","));
                // Запрашиваем информацию о месте по координатам центра карты.
                ymaps
                    .geocode(this._lastCenter, {
                        // Указываем, что ответ должен быть в формате JSON.
                        json: true,
                        // Устанавливаем лимит на кол-во записей в ответе.
                        results: 1,
                    })
                    .then(function (result) {
                        // Будем обрабатывать только ответ от последнего запроса.
                        if (lastCenter == this._lastCenter) {
                            this._onServerResponse(result);
                        }
                    }, this);
            },

            _onServerResponse: function (result) {
                // Данные от сервера были получены и теперь их необходимо отобразить.
                // Описание ответа в формате JSON.
                var members = result.GeoObjectCollection.featureMember,
                    geoObjectData =
                        members && members.length ? members[0].GeoObject : null;
                if (geoObjectData) {
                    this._$content.text(
                        geoObjectData.metaDataProperty.GeocoderMetaData.text
                    );
                }
            },
        });

        var customControl = new CustomControlClass();
        map.controls.add(customControl, {
            float: "none",
            position: {
                top: 10,
                left: 10,
            },
        });
    });
    ```

{% endlist %}
