Documentation
Reference
2.1.50 (current version)
collection
interactivityModel
Interfaces

Controls

Controls are visual objects associated with the map and intended for interaction with users. In most cases, controls are placed in the map viewport.

The Yandex.Maps API includes several built-in sets of controls (for small, medium, and large maps) and gives you the ability to place controls any way you want, as well as implement custom controls.

The set of controls that is added to the map when it is created is specified in the map builder. By default, the 'default' set is enabled, which consists of these controls: search on map, select map type, full-screen mode, zoom slider, geolocation, and the Traffic button. Controls are automatically adapted to the size of the map and the device parameters.

// Example 1: Setting the set of controls when creating the map
var myMap = new ymaps.Map("map", {
    center: [59.93772, 30.313622],
    zoom: 8,
    // Showing the normal set of controls on the map
    // plus an additional route button
    controls: ["default","routeEditor"]
});

// Example 2: Adding controls after creating the map
var myMap2 = new ymaps.Map("map", {
    center: [59.93772, 30.313622],
    zoom: 8,
    // At first, the map only has the zoom slider
    // and the full-screen button
    controls: ["zoomControl", "fullscreenControl"]
});

// Example of working with controls by key
// Adding the "Traffic" button and the map type selector
myMap2.controls
    .add("trafficControl", {
        // Placing the traffic button on the left
        float: "left"
    })
    .add("typeSelector");
// Turning on displaying traffic
myMap2.controls.get("trafficControl").showTraffic();

// Example of working with an instance of a control
// Adding a custom button to the lower-left corner
var myButton = new ymaps.control.Button("My button");
myMap2.controls.add(myButton, {
    float: "none",
    position: {
        bottom: 10, left: 10
    }
});

Sets of controls

SetDescriptionExample

"smallMapDefaultSet"

Set of buttons for small maps (less than 300 pixels wide).

Creating a map with the control set smallMapDefaultSet

var myMap = new ymaps.Map('YMapsID', {
        center: [59.93772, 30.313622],
        zoom: 8,
        controls: ['smallMapDefaultSet']
    );

"mediumMapDefaultSet"

or

"default"

Set of buttons for standard maps (from 300 to 1000 pixels wide).

By default, the map will be created with this set of controls.

"largeMapDefaultSet"

Set of buttons for large maps (more than 1000 pixels wide).

Creating a map with the control set largeMapDefaultSet

var myMap = new ymaps.Map('YMapsID', {
        center: [59.93772, 30.313622],
        zoom: 8,
        controls: ['largeMapDefaultSet']
    );

Standard controls

Components that are intended for creating controls are implemented as classes in the control namespace (for example, control.Button).

Controls are programmatically connected to the map object and stored as a collection that is referenced from the controls field.

There is special storage that allows for assigning a string key to a control class constructor. When adding and removing map controls, they may be specified as references to a control instance, or as a key from this storage.

ControlDescriptionExample

Geolocation

Determines the user's location by calling the browser's standard geolocation function and/or identifying the user's IP address

Adding the geolocation button to the map:

myMap.controls.add('geolocationControl');

Search on a map

Searching for geographical features by name, address, or geographical coordinates.

This control has both a full version in the form of a search bar (for maps with a large horizontal size), or a compact version in the form of a search button (see the picture).

Adding the search box to the map:

myMap.controls.add('searchControl');

Adding the search box to the map with specified parameters:

myMap.controls.add(
    new ymaps.control.SearchControl({
        options: {
            provider: 'yandex#publicMap',
            useMapBounds: true
        }
    })
);

Build a route

Route editor.Adding the route editor to the map:
myMap.controls.add('routeEditor');

Traffic

Displaying traffic on the map.

Allows to enable/disable displaying the traffic layer on the map.

It can be shown as current traffic (traffic “right now”), or as average traffic on roads over time (“typical” traffic).

This control has two versions: detailed (for large maps) with expanded information and a feature for viewing statistics and forecasts, or compact (for small maps) that is just a button for enabling and disabling traffic information (see the picture).

Adding the “Traffic” control to the map:

myMap.controls.add('trafficControl');

Adding the “Traffic” control to the map with automatic enabling and showing traffic conditions:

var trafficControl =
        new ymaps.control.TrafficControl();
myMap.controls.add(trafficControl);
trafficControl.showTraffic();

Select the map type

Selector for the map type to display.

The map type selection button has two versions: detailed (for large maps) and compact (see the picture).

Adding the map type selector to the map (the drop-down list will display all available types):

myMap.controls.add('typeSelector');

Adding the map type selector to the map (the drop-down list will display only the specified types):

myMap.controls.add(
    new ymaps.control.TypeSelector(
        ['yandex#map', 'yandex#hybrid']
    )
);

Full-screen mode

Button for switching to full-screen mode. When this button is clicked, the map expands to fill the entire browser window.

Adding the full-screen buttons to the map:

myMap.controls.add('fullscreenControl');

Zoom slider

Changing the zoom level.

This control has two versions: full (for large maps) with zoom buttons and a zoom scale, and compact (for small maps) with just two buttons (see the picture).

Adding the zoom control panel to the map:

myMap.controls.add('zoomControl');

Measure distances

Displays a scale line and a button for enabling the "Ruler" behavior.

It makes it possible to measure the distance between objects.

Adding measurement controls to the map:

myMap.controls.add('rulerControl');

Positioning controls

Controls can be placed on top of the map in two ways, which are regulated using the float option:

  • Lined up in the upper-right or upper-left corner of the map (float: "right" or float: "left").
  • Positioned at a custom anchor point relative to any corner of the map (float: "none") by setting the position option, containing the offsets in pixels from the edges of the map.

In the first case, controls will be automatically aligned so that they do not intersect each other. The order of the controls is determined by the floatIndex option (controls with larger values are shown closer to the edge).

Custom controls

The API allows for creating your own custom controls for performing any actions you choose.

Most often, controls are implemented as buttons. Use the control.Button class to create a button control.

Two types of button click reactions are supported: after the button is clicked, it stays down (default behavior), or it returns to its initial state. The type of click reaction is set using the selectOnClick option (true/false).

When a button is clicked, the Events details event is always generated. For buttons that remember their state after being clicked, the select or deselect event is also generated (depending on which state the button was in when it was clicked).

You can set a custom icon for a button (using the image option), as well as a fully custom design template, if the standard one is not acceptable.

var myButton =
  new ymaps.control.Button(
    '<b>I'm a button</b>'
  );
myButton.events
  .add(
    'press',
    function () {
      alert('Click');
    }
  )
  .add(
    'select',
    function () {
      alert('Pressed');
    }
  )
  .add(
    'deselect',
    function () {
      alert('Released');
    }
  );
myMap.controls.add(myButton, {
  float: "left"
});
myMap.controls.add(
  new ymaps.control.Button({
    data: {
      content: "button with icon",
      image: "ya.png"
    },
    options: {
      maxWidth: 150
    }
  }
));
var template =
  '<div style="border: 1px solid gray; padding: 3px;">' +
  "{{ data.content }}" +
  "</div>"

myMap.controls.add(
  new ymaps.control.Button({
    data: {
      content: "My button"
    },
    options: {
      layout:
        ymaps.templateLayoutFactory.createClass(
            template
        ),
      maxWidth: 100
    }})
);

The control.Button class implements a control that has a set standard appearance, click reaction, and methods for setting and defining the current state. This button can be included in a composite control.

You can also define a fully custom control that implements the IControl interface. The sandbox has a sample that demonstrates creating a custom control.

Drop-down lists

The "drop-down list" control provides a convenient view of a list of objects that centers the map when clicked.

ControlDescriptionExample

Drop-down list

Drop-down list.

Classes:

control.ListBox — Container for controls.

control.ListBoxItem — List item.

var myListBox = new ymaps.control.ListBox({
    data: {
        content: 'Select a city'
    },
    items: [
        new ymaps.control.ListBoxItem('Moscow'),
        new ymaps.control.ListBoxItem('Novosibirsk'),
        new ymaps.control.ListBoxItem('New York')
    ]
});

myMap.controls.add(myListBox);

Adaptivity

The standard controls in the Yandex.Maps API are adaptive, meaning they automatically adapt to the size of the map and the size of the screen. The images below illustrate how the appearance of controls changes depending on the map size.

The following controls support adaptivity:

The zoom control changes its appearance depending on the height of the map, while the other controls change in accordance with the map's width.

Note. Adaptivity only works for controls that have the float: 'left' or float: 'right' option set. The exception is the zoom control. Because it changes its state depending on the map height, its adaptivity works even if it has float: 'none' set.

Controls can take one of three states: 'small', 'medium', or 'large'. The visual representation on the map is defined for each control state:

StateDescription

'small'

Only the control's icon is shown.

'medium'

Only the text label is shown. For the zoom control and the “Traffic” element, the 'small' and 'medium' states are the same.

'large'

Both the text label and icon are shown.

Note. The zoom control changes its appearance in a slightly different way. For small map sizes, this control is displayed as two buttons; for large map sizes, the zoom slider is displayed in addition to the buttons.

Information about the current state of a control is put in the state field, which has the size property. The example below demonstrates how to determine the current state of a control.

myMap.controls.add('trafficControl');
// Determining the state of the “Traffic” control.
var controlState = myMap.controls.get('trafficControl').state.get('size');

States are managed by control.Manager. When adding another control to the map or changing the map size, the manager checks the state of controls and changes them as necessary. The manager changes the state simultaneously for all the controls that support adaptivity.

If a control's state must be fixed, set the size option for it. This option affects the adaptivity of objects in the following way. If you set one of the three sizes as its value ('small', 'medium', 'large'), the control will always be shown in this size. By default, the option takes the 'auto' value, meaning the control will changes its appearance in accordance with the map size and the number of controls added to the map.

Note. When the size option is set, changes to state.size will not affect the appearance of the control, because the object option takes priority over the state.

// Locking the state of the “Traffic” control. 
// Now it will always be displayed large.
myMap.controls.get('trafficControl').options.set('size', 'large');

The maxWidth option is also defined for each control, as an array of numbers in which each state is assigned a corresponding maximum width. When a control reaches this width, it switches to a more compact format.

The sandbox has samples that demonstrate the behavior of adaptive controls.

Custom adaptive controls

Sometimes there are tasks that can't be accomplished using the standard controls. The Yandex.Maps API gives you the ability to create custom adaptive controls.

To create custom controls, you can use the built-in API classes control.Button and control.ListBox. The layouts for the button and drop-down list are adaptive by default. If the controls have both a text and image set, they will change their appearance as follows:

ButtonDrop-down list

'small'

'small'

'medium'

'medium'

'large'

'large'

The example below shows how to create a custom adaptive button using the control.Button class.

var myButton = new ymaps.control.Button({
      data: {
        // Button text.
        content: "<b>Button</b>",
        // Image of the button icon.
        image: 'my_button.png',
        // Text of the pop-up hint that appears
        // when the mouse points at the button. 
        title: "Click me"
      },
      options: {
        // Because the button will change its appearance in accordance with the map size,
        // we are setting three different maxWidth values for it in the array.
        maxWidth: [28, 150, 178]
      }
);
myMap.controls.add(myButton, float);

Note. The maxWidth option must be set for the control to indicate the maximum size for each of the three states. If you pass a number in this option, the control will not be adaptive.

If you need to set custom rules for changing sizes for a control, use templateLayoutFactory. The example below shows a button that changes its appearance depending on whether it is selected (by default, buttons change their appearance depending on the map width).

var ButtonLayout = ymaps.templateLayoutFactory.createClass([
      '<div alt="{{ data.title }}" class="my-button ',
        '{% if state.size == "small" %}my-button_small{% endif %}',
        '{% if state.size == "medium" %}my-button_medium{% endif %}',
        '{% if state.size == "large" %}my-button_large{% endif %}',
        '{% if state.selected %} my-button_selected{% endif %}">',
        '<img class="my-button__img" src="{{ data.image }}" alt="{{ data.title }}">',
        '<span class="my-button__text">{{ data.content }}</span>',
      '</div>'
    ].join('')),

    button = new ymaps.control.Button({
      data: {
        content: "Push-Push",
        image: 'examples/maps/ru/button_layout/images/pen.gif',
        title: "Push-Push-Push"
      },
      options: {
        layout: ButtonLayout
      }
    });

myMap.controls.add(button, {
  float: "right"
});