Documentation
Reference
2.1.50 (current version)
collection
interactivityModel
Interfaces

Guide for migrating to JSAPI 2.1

This guide contains examples that demonstrate the differences between the JavaScript API versions 2.1 and 2.0, as well as between 2.1 and 1.x. This section only covers API operations that do not have backward compatibility.

Migrating from version 2.0

This section provides examples of working with the JavaScript API versions 2.0 and 2.1. Pay attention to the highlighted code fragments. Each of them has an explanation.

Enabling the API

Version 2.0Version 2.1
<!DOCTYPE html>
  <head>
    <!-- Loading the API -->
    <script src="https://api-maps.yandex.ru/2.0/?lang=ru_RU&load=package.standard" type="text/javascript"></script>
    <script type="text/javascript">
      // If the API loads successfully,
	  // the corresponding function is executed.
      ymaps.ready(function () {
         …
      });
    </script>
   </head>
  ...
</html>

API URL: https://api-maps.yandex.ru/2.0/.

Mandatory parameters:

  • lang — Language.
  • load — Packages to load.

Additional parameters:

  • key — API key.
  • mode — API mode. By default, release (code is obfuscated and API errors are not generated).
  • coordorder — Order of coordinates. Takes the value latlong (latitude, longitude) by default.
  • ns — Namespace. By default, ymaps.

<!DOCTYPE html>
  <head>
    <!-- Loading the API -->
    <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
    <script type="text/javascript">
      // If the API loads successfully,
      // the corresponding function is executed.
      ymaps.ready(function () {
         …
      });
    </script>
   </head>
  ...
</html>

API URL: https://api-maps.yandex.ru/2.1/.

The same parameters are available as in version 2.0.

The load parameter sets modules that must be loaded. This parameter is not mandatory.

By default, all API components are loaded (load=package.full).

The module system is designed so that functionality is loaded at the time when it is actually used. In most cases, there is no need to set the load parameter.

Creating a map

Version 2.0Version 2.1
// Creating a map instance and binding it to 
// a container with the id="YMapsID".
var myMap = new ymaps.Map("YMapsID", {
      // Map center.
      center: [55.76, 37.64],
      // Zoom level.
      zoom: 10,
      // Map type.
      type: "yandex#satellite"
    });

By default, the map is created without controls.

// Creating a map instance and binding it to
// a container with the id="YMapsID".
var myMap = new ymaps.Map("YMapsID", {
      center: [55.76, 37.64],
      zoom: 10,
      type: "yandex#satellite",
      // The map will be created without
      // controls. 
      controls: []
    });

By default, the map is created with the standard controls: search on map, select map type, full-screen mode, zoom slider, geolocation, and the "Traffic" button.

If you need to create the map without controls, pass an empty array in the constructor in the controls field.

See the section Controls for instructions on how to add the desired controls to the map.

Map behavior

Version 2.0Version 2.1

The following behaviors are enabled by default: 'drag', 'multiTouch', 'dblClickZoom', and 'rightMouseButtonMagnifier'.

By default, the same behaviors are enabled as in version 2.0, plus 'scrollZoom'.

Geo objects

Setting the placemark style

Version 2.0Version 2.1
// Placemark with one of the standard icons.
var myPlacemark = new ymaps.Placemark(
      // Placemark coordinates.
      [55.8, 37.6],
      // Placemark data.
      {},
      // Placemark options.
      {
        preset: 'twirl#greenIcon'
      }
    );

// Creating a placemark with a custom icon.
var myPlacemark2 = new ymaps.Placemark([55.8, 37.6],
      {},
      { 
        // Custom image for the placemark icon.
        iconImageHref: '/path/to/icon.png',
        // Placemark dimensions.
        iconImageSize: [30, 42],
        // The icon's offset from the upper-left corner
        // relative to its "tail".
        iconImageOffset: [-3, -42]
      }
    );

Placemarks can only be assigned colors from the selection provided.

// Placemark with one of the standard icons.
// The list of standard styles is given in the Reference
// in the section option.preset.storage.
var myPlacemark = new ymaps.Placemark(
      [55.8, 37.6],
      {},
      {
        preset: 'islands#greenCircleIcon'
      }
    );

// Creating a placemark with a custom icon.
var myPlacemark2 = new ymaps.Placemark(
      [55.8, 37.6],
      {},
      {
        // One of two standard placemark layouts
        // with an icon image:
        // - default#image - without content.
        // - default#imageWithContent - with text
        // in the icon.
        iconLayout: 'default#image',
        iconImageHref: '/path/to/icon.png',
        iconImageSize: [20, 30],
        iconImageOffset: [-10, -20]
      }
    );

When setting a custom icon image, you must specify the layout: 'default#image' option.

Placemarks have a vector representation, so custom colors can be set for their icons (except placemarks that stretch to fit the content). Note that this feature is not supported in the IE8 browser (icons will be the standard blue color).

// Creating a placemark with a custom color.
var myPlacemark = new ymaps.Placemark(
      [55.8, 37.6],
      {},
      {
        // Placemark style as a circle.
        preset: 'islands#circleIcon',
        // Placemark color. The iconColor option can be 
        // set together with the preset option,
        // if the latter does not have the value 'stretchyIcon'.
        iconColor: '#00000'
      }
    );

Creating a custom geo object layout

Version 2.0Version 2.1
var myIconContentLayout = ymaps.templateLayoutFactory.createClass('<div class="square_layout"></div>'});

var squarePlacemark = new ymaps.Placemark(        [55.725118, 37.682145], {
      hintContent: 'Placemark with square layout'
      }, {
        iconLayout: myIconContentLayout
      }
    );

When geo objects are added to the map, the corresponding elements are added to the DOM tree. They are added above the container where the subscription to map events is implemented. In this way, events that occur on a geo object are tracked on the DOM level.

var myIconContentLayout = ymaps.templateLayoutFactory.createClass('<div
 class="square_layout"></div>');
var squarePlacemark = new ymaps.Placemark(
      [55.725118, 37.682145],
      {
        hintContent: 'Placemark with square layout'
      }, {
        iconLayout: myIconContentLayout,
        // Describing the hotspot shape
        // "Rectangle".
        iconShape: {
          type: 'Rectangle',
          // A rectangle is defined as two points - 
          // the upper-left and lower-right corners.
          coordinates: [
            [-25, -25], [25, 25]
          ]
        }
      }
    );

When adding geo objects to the map, their corresponding elements are added to the DOM tree under the layer where subscribing to map events is implemented. This means that geo object events are not tracked on the DOM level.

Interactivity of geo objects is implemented using hotspots, which are bound to the events layer. For geo objects with the standard layout, hotspots are defined automatically.

When creating a custom geo object layout, you must independently define the hotspot shape using the iconShape option. Its fields specify the geometry type that is accepted by the hotspot (for example, rectangle or circle), as well as a description of its contour (for a circle, for example, this is the coordinates of its center and the length of its radius in pixels).

For a detailed example of setting the hotspot shape, see the sandbox.

Clusterization

Cluster balloon and hint

Version 2.0Version 2.1
cluster.balloon.open();

For each cluster, a balloon manager is created in the balloon field.

clusterer.balloon.open(clusterPlacemark);
clusterer.hint.open(clusterPlacemark);

A single balloon/hint manager is created in the balloon/hint field of the clusterer.

Working with clusterer objects after adding them to the map

Version 2.0Version 2.1
var placemarks = [
      new ymaps.Placemark([44, 55]),
      new ymaps.Placemark([34, 45])
    ];
clusterer.add(placemarks);

clusterer.events.add('objectsaddtomap', function () {
  // Getting data about the state of
  // an object inside the cluster.
  var geoObjectState = clusterer.getObjectState(placemarks[1]);
  // Checking whether the object
  // is inside the map viewport.
  if (geoObjectState.isShown) {
    // If the object is in the cluster,
    // the cluster balloon opens with the object selected.
    if (geoObjectState.isClustered) {
      geoObjectState.cluster.state.set('activeObject', placemarks[1]);
      geoObjectState.cluster.balloon.open()
    } else {
      // If the object is not in the cluster,
      // its own balloon is opened.
      placemarks[1].balloon.open();
    }
  }
});

Since objects are added asynchronously by default, data processing can only be done after an event, signaling the end of adding child objects of the clusterer to the map.

var placemarks = [
      new ymaps.Placemark([44, 55]),
      new ymaps.Placemark([34, 45])
    ];
clusterer.add(placemarks);

// Getting data about the state of
// an object inside the cluster.
var geoObjectState = clusterer.getObjectState(placemarks[1]);
// Checking whether the object
  // is inside the map viewport.
if (geoObjectState.isShown) {
  // If the object is in the cluster,
    // the cluster balloon opens with the object selected.
  if (geoObjectState.isClustered) {
    geoObjectState.cluster.state.set('activeObject', placemarks[1]);
    clusterer.balloon.open(geoObjectState.cluster);     } else {
    // If the object is not in the cluster,
      // its own balloon is opened.
    placemarks[1].balloon.open();
  }
}

The clusterer's child objects (clusters and placemarks that are not in any cluster) are added to the map synchronously.

Changing the color of a cluster icon

Version 2.0Version 2.1
var options = ymaps.option.presetStorage.get('twirl#redClusterIcons');

cluster.options.set({
   icons: options.clusterIcons,
   iconContentLayout: options.clusterContentLayout
});

The change the color of a cluster icon, you must set the following options for it:

  • icons — Array of references to icon images (small, medium, and large).
  • iconContentLayout — Layout for the cluster placemark content.

You can also control the colors of clusters using the preset option, which specifies the key of the desired style. This option can only be set for the entire clusterer. The color will be set for the icons of all of its clusters.

cluster.options.set('preset', 'islands#redClusterIcons');

You can also change the color of the cluster icon using the preset option, which specifies the key of the desired style.

Setting options for objects that make up a cluster

Version 2.0Version 2.1
clusterer.options.set({
  clusterBalloonLayout: myClusterBalloonLayout,
  balloonLayout: myPlacemarkBalloonLayout
});

Options that are set via the clusterer are applied to all its child objects: both to single placemarks (that are not in any of the clusters), as well as to cluster placemarks.

If options must be set only for cluster placemarks, the option name should be specified with the “cluster” prefix.

However, if only individual placemarks should be affected, in any case you will have to set options both for the separate placemarks as well as for the cluster placemarks.

clusterer.options.set({
  clusterBalloonLayout: myClusterBalloonLayout,
  geoObjectBalloonLayout: myPlacemarkBalloonLayout
});

All options for the clusterer's child objects are set with the corresponding prefixes: with the “cluster” prefix for cluster placemarks, and with the “geoObject” prefix for separate placemarks. In this way, the options of child objects are not dependent on each other.

Map controls

Available controls

Version 2.0Version 2.1
  • control.Button
  • control.Group
  • control.ListBox
  • control.ListBoxItem
  • control.ListBoxSeparator
  • control.MapTools
  • control.MiniMap
  • control.RadioGroup
  • control.RollupButton
  • control.RouteEditor
  • control.ScaleLine
  • control.SearchControl
  • control.SmallZoomControl
  • control.ToolBar
  • control.ToolBarSeparator
  • control.TrafficControl
  • control.TypeSelector
  • control.ZoomControl
  • control.Button
  • control.ListBox
  • control.ListBoxItem
  • control.RouteEditor
  • control.RulerControl
  • control.SearchControl
  • control.TrafficControl
  • control.TypeSelector
  • control.ZoomControl

Added new controls:

  • control.FullscreenControl — full-screen mode
  • control.GeolocationControl — geolocation

No longer supported:

  • control.Group
  • control.ListBoxSeparator
  • control.MapTools
  • control.MiniMap
  • control.RadioGroup
  • control.RollupButton
  • control.ScaleLine
  • control.SmallZoomControl
  • control.ToolBar
  • control.ToolBarSeparator

Adding controls to the map

Version 2.0Version 2.1
// Adding the standard set of buttons.
myMap.controls.add("mapTools")
  // Adding zoom control buttons.
  .add("zoomControl")
  // Adding the list of map types.
  .add("typeSelector");
// The first method for defining controls —
// — via the map constructor when creating the map.
var myMap1 = new ymaps.Map("YMapsID", {
      center: [55.76, 37.64],
      zoom: 10,
      controls: ['zoomControl', 'searchControl']
    });

// The second method is via the 'controls" field 
// after creating the map.
myMap1.controls.add('typeSelector');

// If a map must be created without controls,
// in its constructor, pass an empty array
// in the controls field.
var myMap2 = new ymaps.Map("YMapsID", {
      center: [55.76, 37.64],
      zoom: 10,
      controls: []
    });

By default, the map is created with the standard controls: search on map, select map type, full-screen mode, zoom slider, geolocation, and the "Traffic" button.

The desired controls can be defined in two ways: the same as in version 2.0, or via the map constructor when creating the map.

Attention! When attempting to add controls with identical keys, an error occurs. For example, the following code will lead to an error:
// By default, the map is created with the
//  standard controls: search on map,  
// select map type, full-screen mode,
// zoom slider, geolocation,
// and the "Traffic" button.
var myMap = new ymaps.Map("YMapsID", {
      center: [55.76, 37.64],
      zoom: 10
    });

// An error will occur, because the zoom slider
// is already added to the map by default.
myMap.controls.add('zoomControl');

If you need to create the map without controls, pass an empty array in the constructor in the controls field.

The controls are adaptive, meaning they can adapt to the size of the map and the size of the screen. For example, for large map sizes, the controls display both the text label and icon; for medium sizes, they only show the text; for small sizes, they only show the icon.

For more information, see the Controls section in the Developer's guide.

Positioning controls

Version 2.0Version 2.1
myMap.controls
  .add('zoomControl', { left: 5, top: 5 })
  .add('typeSelector')
  .add('mapTools', { left: 35, top: 5 });
myMap.controls
  // The control will be placed in 
  // the upper-right corner with the specified offset.
  .add('zoomControl', {
    float: 'none', 
    position: { 
      top: 5, 
      right: 10
    }
  })
  // The control will be placed in the upper-left corner.
  .add('traffic', { float: left });

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.

Balloon

Version 2.0Version 2.1
var myPlacemark = new ymaps.Placemark([55.76, 37.64], {
        balloonContent: 'I'm a balloon'
    });
var myPlacemark = new ymaps.Placemark([55.76, 37.64], {
        balloonContent: 'I'm a balloon'
    }, {
      balloonPanelMaxMapArea: 0
    });

If the map has small dimensions, the balloon is displayed as a panel in the lower part of the map. If the balloon must be displayed as a pop-up window over the placemark, set the option balloonPanelMaxMapArea: 0.

Balloon that goes off the map.

Version 2.0Version 2.1
var myPlacemark = new ymaps.Placemark([55.76, 37.64], {
        balloonContent: 'I went off the map'
    }, {
      // The balloon is in the container
      // 'movableOuters' (not in the overlays container)
      // and goes past the edge of the map.
      balloonPane: 'movableOuters',
      balloonShadowPane: 'movableOuters'
    });

In this code fragment, the movement of the balloon's anchor point (i.e. its “tail”) is not tracked, so the balloon will be displayed even if it goes completely out of the map's boundaries.

In order to display the balloon outside of the map with a shadow, set the option balloonShadowPane: 'movableOuters'.

var myPlacemark = new ymaps.Placemark([55.76, 37.64], {
        balloonContent: 'I went off the map'
    }, {
      balloonPane: 'outerBalloon'
    });

In this example, the balloon is displayed even if the anchor point is not in the map viewport. The sandbox has a detailed example that implements tracking the movement of the balloon's anchor point relative to the map's boundaries.

Overlays

getOverlay method

Version 2.0Version 2.1

Returns the overlay of an entity (geo object, balloon, or hint) or null. Does not support working in asynchronous mode.

Asynchronous. Returns the promise object, which is confirmed by the overlay object at the time it is actually created, or is rejected with an appropriate error message.

Methods that return the layout (getLayout, getShadowLayout and so on)

Version 2.0Version 2.1

Synchronous. Return the layout of an entity (control, geo object, balloon, or hint).

Asynchronous. Return the promise object, which is confirmed by the layout at the time it is actually created, or is rejected with an appropriate error message.

Migrating from version 1.x

This section contains code example for executing the main operations with the Yandex.Maps JavaScript API versions 1.1 and 2.1.

Enabling the API

Version 1.1Version 2.1
<!DOCTYPE html>
  <head>
    <!-- Loading the API-->
    <script src="https://api-maps.yandex.ru/1.1/index.xml?key=API-ключ" type="text/javascript"></script>
    <script type="text/javascript">
      /* If the API loads successfully, the corresponding function is executed */
      YMaps.jQuery(function () {
        …
      });
    </script>
  </head>
  ...
</html>

API URL: https://api-maps.yandex.ru/1.1/index.xml.

The API key must be passed.

The loaded API includes the jQuery library.

<!DOCTYPE html>
  <head>
    <!-- Loading the API-->
    <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
    <script type="text/javascript">
      /* If the API loads successfully,
         the corresponding function is executed */
      ymaps.ready(function () { 
        …
      });
    </script> 
  </head>
  ...
</html>

API URL: https://api-maps.yandex.ru/2.1/.

The API key is not required.

The lang parameter is required.

Available parameters:

  • lang — The language (mandatory parameter).
  • key — API key.
  • load - Modules to load.
  • mode — API mode. By default, release (code is obfuscated and API errors are not generated).
  • coordorder — Order of coordinates. Takes the value latlong (latitude, longitude) by default.
  • ns — Namespace. By default, ymaps.

The API does not include the jQuery library and allows modular loading (minimizes traffic).

Creating a map

Version 1.1Version 2.1
/* Creating a map instance and binding it  
   to a container with the id="YMapsID" */
var myMap = new YMaps.Map(YMaps.jQuery("#YMapsID")[0]);

// Setting the map's center, type, and zoom
myMap.setCenter(
  // Map center    
  new YMaps.GeoPoint(37.64, 55.76), 
  // Zoom level
  10, 
  // Map type
  YMaps.MapType.SATELLITE
)

The map center and zoom level are set after the map is initialized.

/* Creating a map instance and binding it to
  a container with the id="YMapsID" */
var myMap = new ymaps.Map("YMapsID", {
      // Map center
      center: [55.76, 37.64],
      // Zoom level
      zoom: 10,
      // Map type
      type: "yandex#satellite"
    });

The map center and zoom level are set when the map is initialized.

By default, the map will be created with the standard controls.

Map parameters

Changing the map viewport

Version 1.1Version 2.1
myMap.setBounds(new YMaps.GeoBounds(
  /* Coordinates of the southwest corner of the
     map's viewport */
  new YMaps.GeoPoint(0, 0), 
  /* Coordinates of the northeast corner of the
       map's viewport */
  new YMaps.GeoPoint(40, 40);
  )
)
myMap.setBounds([
  /* Coordinates of the southwest corner of the
     map's viewport */
  [0, 0],
  /* Coordinates of the northeast corner of the
       map's viewport */
  [40, 40]
  ], {
      // Enable checking for available
      // zoom range (avoids
      // the risk of getting "gray tiles")
      checkZoomRange: true,
      // Map movement can be animated
      duration: 500
  }
)

Smoothly moving the map center

Version 1.1Version 2.1
myMap.panTo(
  // Coordinates of the new map center
  new YMaps.GeoPoint(37.609,55.753), {
    /* Movement options:
       allow reducing and then increasing the
       map zoom when moving between points  */   
    flying: true
  }
)
myMap.panTo(
  // Coordinates of the new map center
  [55.753, 37.609], {
    /* Movement options:
       allow reducing and then increasing the
       map zoom when moving between points 
     */
    flying: true
  }
)

Getting the maximum and minimum map zoom

Version 1.1Version 2.1
/* Determining the maximum value of the 
   zoom level for the specified viewport
   on the map */
var maxZoom = myMap.getMaxZoom(
      new YMaps.GeoBounds(
        new YMaps.GeoPoint(0, 0), 
          new YMaps.GeoPoint(40, 40)
      )
    );

/* Determining the minimum value  of the
   zoom level for the specified viewport
   on the map */
var minZoom = myMap.getMinZoom(
      new YMaps.GeoBounds(
        new YMaps.GeoPoint(0, 0),
        new YMaps.GeoPoint(40, 40)
      )
    );

Getting the minimum and maximum zoom values is a synchronous operation (all necessary data is loaded when enabling the API).

The maximum and minimum zoom values are determined for the specified map viewport.

/* Determining the maximum and minimum 
  values for the zoom level
  (for the map center) */
myMap.zoomRange.get(
  /* Coordinates of the point where the values
     of the zoom levels are defined */ 
  [55.8,37.6]
).then(function (zoomRange) {
    // zoomRange[0] - minimum zoom
    // zoomRange[1] - maximum zoom
    ...
});
// Alternative: getting a range
// of zooms without creating the map
ymaps.getZoomRange(
  // Map type
  'yandex#map',
  /* Coordinates of the point where the values 
     of the zoom levels are defined */ 
  [55.8,37.6]
).then(function (zoomRange) {
    // zoomRange[0] - minimum value
    // zoomRange[1] - maximum value
    ...
});
               

Getting the minimum and maximum zoom values is an asynchronous operation (when calling the method, a server request is formed and a promise object is returned).

The maximum and minimum zoom values are determined for the specified point on the map.

Map behavior

Enabling map behaviors

Version 1.1Version 2.1
// Enabling needed behaviors after the map is created
myMap.enableRuler();
myMap.enableScrollZoom();

Map behaviors can only be enabled after the map has been initialized.

/* When creating the map, in addition to "default" behaviors,
   we are enabling some additional behaviors (ruler) */ 
var myMap = new ymaps.Map("map", {
      center: [59.93, 30.31],
      zoom: 10,
      behaviors: ["default", "ruler"]
    });

// Enabling behaviors after the map is created
myMap.behaviors.enable("routeEditor");

Map behaviors can be enabled either during map creation, or after it.

Disabling map behaviors

Version 1.1Version 2.1
// Disabling behaviors only after the map is created
myMap.disableDragging();
myMap.disableScrollZoom();

Map behaviors are disabled after the map has been initialized.

/* When initializing the map, we are disabling all behaviors 
   except scrollZoom */
var myMap = new ymaps.Map("map", {
      center: [59.93, 30.31],
      zoom: 10,
      behaviors: ["scrollZoom"]
    });

// Disabling a behavior after map initialization
myMap.behaviors.disable("scrollZoom");

Map behaviors can be disabled either during map initialization, or after it.

Adding geo objects to the map

Version 1.1Version 2.1
myMap.addOverlay(geoObject)

All geo objects are added to the map using the addOverlay() method.

myMap.geoObjects.add(geoObject);

All geo objects are added to the map via the map.geoObjects global collection using the add() method.

Placemark

Version 1.1Version 2.1
// Creating a placemark 
var myPlacemark = new YMaps.Placemark(
      // Placemark coordinates
      new YMaps.GeoPoint(37.6, 55.8), {
        /* Placemark options:
           - flag for placemark dragging */
        draggable: true,
        /* - show placemark icon 
             when opening balloon */
        hideIcon: false
      }
    );

// Setting placemark icon content
myPlacemark.name = "Moscow";
// Setting balloon content
myPlacemark.description = "Capitol of Russia";

// Adding the placemark to the map
myMap.addOverlay(myPlacemark); 
// Creating a placemark
var myPlacemark = new ymaps.Placemark(
      // Placemark coordinates
      [55.8, 37.6], {
        /* Placemark properties:
           - content of the placemark icon */
        iconContent: "Moscow",
        // - content of the placemark balloon
        balloonContent: "Capital of Russia"
      }, {
        /* Placemark options:
           - flag for placemark dragging */
        draggable: true,
        /* - show placemark icon 
             when opening balloon */
        hideIconOnBalloonOpen: false
      }
    );

// Adding the placemark to the map
myMap.geoObjects.add(myPlacemark);

Changing the placemark icon

Version 1.1Version 2.1
// A placemark with one of the standard icons
var myPlacemark = new YMaps.Placemark(
      // Placemark coordinates
      new YMaps.GeoPoint(37.6, 55.8),
      // Placemark options
      {
        style: 'default#greenPoint'
      }
    );
    
// Setting a custom placemark icon
var myStyle = new YMaps.Style();
myStyle.iconStyle = new YMaps.IconStyle();
// Icon URL
myStyle.iconStyle.href = '/path/to/icon.png';
// Icon size
myStyle.iconStyle.size = new YMaps.Point(18, 29);
// Icon "tail" position
myStyle.iconStyle.offset = new YMaps.Point(-9, -29);

// Creating a placemark with a non-standard icon
var myPlacemark2 = new YMaps.Placemark(
      // Placemark coordinates
      new YMaps.GeoPoint(37.6, 55.8),
      // Placemark options
      {
        style: myStyle
      }    
    );
// Placemark with one of the standard icons
var myPlacemark = new ymaps.Placemark(
      // Placemark coordinates
      [55.8, 37.6],
      // Placemark data
      {},
      // Placemark options
      {
        preset: 'islands#greenCircleIcon'
      }
    );

// Creating a placemark with a nonstandard icon
var myPlacemark2 = new ymaps.Placemark(
      // Placemark coordinates
      [55.8, 37.6],
      // Placemark data
      {},
      // Placemark options
      {
        // One of two standard layouts
        // for placemarks with picture icons:
        // - default#image - without content
        // - default#imageWithContent - with text
        // - content in the icon
        iconLayout: 'default#image',
        // Icon URL
        iconImageHref: '/path/to/icon.png',
        // Icon size
        iconImageSize: [20, 30],
        // Position of the icon's "tail"
        iconImageOffset: [-10, -20]
      }
    );

Balloon

Version 1.1Version 2.1
myMap.openBalloon(
  // Balloon coordinates
  new YMaps.GeoPoint(37.6, 55.7),
  // Balloon content
  "Moscow", {
    /* Balloon options:
       - the balloon has a Close button */
    hasCloseButton: true
  }
);
myMap.balloon.open(
  // Balloon coordinates
  [55.76, 37.64], {
    /* Balloon properties:
       - balloon content */
    content: "Moscow"
  }, {
    /* Balloon options:
       - the balloon has a Close button */ 
    closeButton: true
  }
);

Pop-up hint

Version 1.1Version 2.1
myMap.hint.show(
  // Hint coordinates
  myMap.converter.coordinatesToLocalPixels(myMap.getCenter()), 
  // Hint content
  "Moscow", {
    /* Hint options:
       - timeout for showing the hint */
    showTimeout: 2000
  }
)

The position of the pop-up hint is set by local pixel coordinates.

myMap.hint.show(
  // Hint coordinates
  myMap.getCenter(), 
  // Hint content
  "Moscow", { 
    /* Hint options:
       - timeout for showing the hint */
    showTimeout: 2000
  }
)

The position of the pop-up hint is set in geographic coordinates.

Polyline

Version 1.1Version 2.1
// Creating a polyline
var myPolyline = new YMaps.Polyline(
      // Polyline coordinates
      [
        new YMaps.GeoPoint(37.7, 55.7),
        new YMaps.GeoPoint(37.7, 55.8),
        new YMaps.GeoPoint(37.8, 55.8),
        new YMaps.GeoPoint(37.8, 55.7),
        new YMaps.GeoPoint(37.7, 55.7)
      ], {
        /* Polyline options:
           - disabling the balloon Close button */
        hasCloseButton: false
      }
);

// Creating polyline styles
var s = new YMaps.Style();
s.lineStyle = new YMaps.LineStyle();
// Line color and transparency
s.lineStyle.strokeColor = "0000FF55";
// Line width
s.lineStyle.strokeWidth = "5";

// Adding styles to the map storage for styles
YMaps.Styles.add("example#CustomLine", s);

// Setting styles for a polyline
myLine.setStyle("example#CustomLine");

// Setting polyline balloon content
myPolyline.setBalloonContent("Polyline");

// Adding a polyline to the map
myMap.addOverlay(myPolyline);
// Creating a polyline
var myPolyline  = new ymaps.Polyline([
      // Coordinates of polyline vertexes
      [55.80, 37.30],
      [55.80, 37.40],
      [55.70, 37.30],
      [55.70, 37.40]
    ], {
      /* Polyline properties:
         - polyline balloon */
      balloonContent: "Polyline"
      }, {
        /* Polyline options: 
           - disabling the balloon Close button */
        balloonCloseButton: false,
        // - line color and transparency
        strokeColor: "0000FF55",
        // - line width
        strokeWidth: 5
      }
    );

// Adding a polyline to the map
myMap.geoObjects.add(myPolyline);

Polygon

Version 1.1Version 2.1
// Creating a polygon
var myPolygon = new YMaps.Polygon([
      // Polygon coordinates 
      new YMaps.GeoPoint(37.7, 55.7),
      new YMaps.GeoPoint(37.7, 55.8),
      new YMaps.GeoPoint(37.8, 55.8),
      new YMaps.GeoPoint(37.8, 55.7)
    ]
),
  
    // Creating polygon styles
    style = new YMaps.Style();
style.polygonStyle = new YMaps.PolygonStyle();
// Flag for using fill
style.polygonStyle.fill = true;
// Flag for drawing the outline
style.polygonStyle.outline = true;
// Line width
style.polygonStyle.strokeWidth = 10;
// Line color and transparency
style.polygonStyle.strokeColor = "ffff0088";
// Fill color and transparency
style.polygonStyle.fillColor = "ff000055";

// Setting styles for a polygon
myPolygon.setStyle(style);

// Setting content of the polygon pop-up hint
myPolygon.setHintContent = ("Polygon");

// Adding a polygon to the map
myMap.addOverlay(myPolygon);

If the coordinates of the first and last vertexes on the polygon do not match, these vertexes will be automatically connected when drawing it.

// Creating a polygon
var myPolygon = new ymaps.Polygon([
      // Polygon coordinates
      [
        [55.75, 37.50],
        [55.76, 37.60],
        [55.80, 37.70],
        [55.69, 37.72]
      ]
    ], {
      /* Polygon properties:
         - hint content */
      hintContent: "Polygon"            
    }, {
      /* Polygon options:
         - flag for using fill */ 
      fill: true,
      // - flag for drawing the outline
      stroke: true,
      // - line width
      strokeWidth: 5,             
      // - line color and transparency
      strokeColor: "ffff0088",
      // - fill color and transparency
      fillColor: "ff000055"
    });
 
// Adding a polygon to the map
myMap.geoObjects.add(myPolygon);

If the coordinates of the first and last vertexes on the polygon do not match, when creating this polygon another vertex will be added that coincides with the first one.

Collections

Creating a collection

Version 1.1Version 2.1
var myCollection = new YMaps.GeoObjectCollection();
var myCollection = new ymaps.GeoObjectCollection();

Displaying collection items on the map

Version 1.1Version 2.1
// Creating a placemark
var myPlacemark = new YMaps.Placemark(new YMaps.GeoPoint(37.64, 55.76));

// Adding an object (placemark) to a collection
myCollection.add(myPlacemark);

// Adding the collection to the map
myMap.addOverlay(myCollection);
// Creating a placemark
var myPlacemark = new ymaps.Placemark([55.8,37.6]);

// Adding an object (placemark) to a collection
myCollection.add(myPlacemark);

// Adding the collection to the map
myMap.geoObjects.add(myCollection);

Deleting items from a collection

Version 1.1Version 2.1
// Deleting a single item from a collection
myCollection.remove(myPlacemark);

// Deleting all items from a collection
myCollection.removeAll();
// Deleting a single item from a collection
myCollection.remove(myPlacemark);

// Deleting all items from a collection
myCollection.removeAll();

Setting styles for collection items

Version 1.1Version 2.1
// Setting styles for a collection when creating it
var myCollection = new YMaps.GeoObjectCollection("default#greenPoint"); 

// Setting styles for a collection after creating it
myCollection.setStyle("default#redPoint")
// Setting styles for a collection when creating it
var myCollection = new ymaps.GeoObjectCollection({}, {
      preset: "twirl#greenIcon" 
    });

// Setting styles for a collection after creating it
myCollection.options.set("preset", "twirl#redIcon");

Map controls

Adding controls to the map

Version 1.1Version 2.1
// Adding the standard set of buttons
myMap.addControl(new YMaps.ToolBar());
// Adding zoom control buttons
myMap.addControl(new YMaps.Zoom());
// Adding the list of map types
myMap.addControl(new YMaps.TypeControl());

The standard set of controls is created automatically when the map is created.

Events

Adding a map event handler

Version 1.1Version 2.1
/* When the map is clicked, a balloon appears 
   with the coordinate values at the click point */
YMaps.Events.observe(myMap, myMap.Events.Click, function (myMap, mEvent) {
  myMap.openBalloon(
    // Balloon position
    mEvent.getGeoPoint(),
    // Balloon content
    "Value: " + mEvent.getGeoPoint()
  );
});
/* When the map is clicked, a balloon appears
   with the coordinate values at the click point */
myMap.events.add("click", function(e) {
  myMap.balloon.open(
    // Balloon position
    e.get("coords"), {
      // Balloon properties:
      // Balloon content
      contentBody: "Value: " + e.get("coords")
    }
  )
});

Deleting an event handler

Version 1.1Version 2.1
/* Deleting an event handler after
   the event has occurred */
var myEventListener = YMaps.Events.observe(map, map.Events.Click, 
      function (map, mEvent) {
        alert("Click!");
        myEventListener.cleanup();
      }
    );
// One-time subscription to an event
var onClick = function() {
      alert("Click!");
      myMap.events.once("click", onClick);
    };

myMap.events.add("click", onClick);

Geosearch

Forward geocoding

Version 1.1Version 2.1
var geocoder = new YMaps.Geocoder(
      /* String with the address
         to be geocoded */
      "Moscow", {
        /* Search options:
           - search area */
        boundedBy: myMap.getBounds(),
        // - search only in this area
        strictBounds: true,
        // - required number of results
        results: 1
    });

/* Placing the resulting collection
   of geo objects on the map */
myMap.addOverlay(geocoder);
var myGeocoder = ymaps.geocode(
      /* String with the address
         to be geocoded */
      "Moscow", {
        /* Search options:
            - search area */
        boundedBy: myMap.getBounds(),
        // - search only in this area
        strictBounds: true,
        // - required number of results
        results: 1
    });

/* After the search returns results, the
   callback function is called*/
myGeocoder.then(function (res) {
  /* Putting the resulting collection of 
     geo objects on the map */
  myMap.geoObjects.add(res.geoObjects);
});

Handling geocoder events

Version 1.1Version 2.1
/* Adding the "Load" event handler
   (geocoding finished successfully) */
YMaps.Events.observe(geocoder, geocoder.Events.Load,
  function () {
    if (this.length()) {
      // Adding the first received object to the map
      myMap.addOverlay(this.get(0));
      // Centering the map on the added object
      myMap.panTo(this.get(0).getGeoPoint())
    } else {
      alert("No results found");
    }
  }
)

/* Adding the "Fault" event handler (an error
   occurred during geocoding) */
YMaps.Events.observe(geocoder, geocoder.Events.Fault, 
  function (error) {
      alert("An error occurred: " + error.message)
  }
)
// The search result is passed to the callback function
myGeocoder.then(
  function (res) {
    if (res.geoObjects.getLength()) {
      // point - the first item in the collection of found objects
      var point = res.geoObjects.get(0);
      // Adding the resulting item to the map
      myMap.geoObjects.add(point);
      // Centering the map on the added object
      myMap.panTo(point.geometry.getCoordinates());
    }
  },
  // Error handling
  function (error) {
    alert("An error occurred: " + error.message);
  }
)

Router

Creating a route

Version 1.1Version 2.1
var router = new YMaps.Router([
      // List of points to visit
      'Arbatskaya',
      'Kropotkinskaya',
      // 'Tretyakovskaya' metro station
      new YMaps.GeoPoint(37.62561,55.74062)
    ],
    // Kropotkinskaya is a throughpoint
    [1], {
      /* Router options: 
         - automatically position the map */
      viewAutoApply: true 
    });

Route points can be set by specifying either their coordinates (an object of the YMaps.GeoPoint class), or the address.

var myRouter = ymaps.route([
      // List of points to visit
      'Moscow, Arbatskaya metro station', {
        // Kropotkinskaya — throughpoint
        type: "viaPoint",                   
        point: "Moscow, Kropotkinskaya metro station"
      },
      [55.74062, 37.62561] // "Tretyakovskaya" metro station
    ], {
      /* Router options:
         - automatically position the map */
      mapStateAutoApply: true 
    });

Route points can be set in one of the following formats:

  • the address of the point.
  • an object with the fields type (type of point) and point (address of the point).
  • an array of point coordinates.

Adding a route to the map

Version 1.1Version 2.1
// Adding a route to the map
myMap.addOverlay(router);
/* After the route is built, the callback
   function is called */ 
myRouter.then(function(route) {
  // Adding the route to the map
  myMap.geoObjects.add(route);
});

Handling router events

Version 1.1Version 2.1
/* Adding a "Success" event handler
   (route was built successfully) */
YMaps.Events.observe(router, router.Events.Success, function() {
  // Setting the text for placemarks
  router.getWayPoint(0).setIconContent("A");
  router.getWayPoint(1).setIconContent("B");
  // Adding the route to the map
  myMap.addOverlay(router);
})

/* Adding the "Error" event handler (route was not
   built successfully) */
YMaps.Events.observe(router, router.Events.RouteError, function (link, num) {
  alert("Cannot built a route to the point " +
num);
})
/* If the route is built successfully, the callback
   function is called */
myRouter.then(function(route) {
    /*Setting the content of placemarks at the first and 
       last points */
    var points = route.getWayPoints();
    points.get(0).properties.set("iconContent", "A");
    points.get(1).properties.set("iconContent", "B");
    //Adding the route to the map
    myMap.geoObjects.add(route);
  },
  // Error handling
  function (error) {
    alert("An error occurred: " + error.message);
  }
)