Enabling the API

In order to use the Yandex Maps API, the API components must be loaded together with the page code, like a normal external JavaScript file. The most common method of enabling external scripts is using the script element in the HTML document header. For example:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="https://api-maps.yandex.ru/2.1/?apikey=Your API key&lang=en_RU"
type="text/javascript"></script>
    </head>
</html>

Alert

The API components can only be loaded over the HTTPS protocol.

For free versions of the API, the download link has the format:

https://api-maps.yandex.ru/`<`version number`>`/?apikey=Your API key&lang=<language ID>&<additional parameters>

For commercial versions of the API, the download link has the format:

https://enterprise.api-maps.yandex.ru/`<`version number`>`/?apikey=Your API key&lang=<language ID>&<additional parameters>

More information about API versions.

Alert

For users with the browser IE8, IE9, or IE10, the 2.1.oldie.1 version is enabled, even if a different API version is indicated in the connection link. The 2.1.oldie.1 version has the same functionality as version 2.1.59, without later updates.

If you need to support IE8, IE9, and IE10 browsers, follow the reference guide for version 2.1.59 when writing your code. Using the functionality from later versions might cause the API to work incorrectly in IE8, IE9, and IE10.

Note that in the standard browser for the Android mobile operating system and Apple iOS earlier than version 3.2, the zoom gesture causes the zoom of the entire page to increase using the browser resources. To disable processing zoom gestures, add the following code to the page's "head" tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no, maximum-scale=1" /> 

For more information, see the description of the "viewport" metatag in the Safari HTML Reference.

API loading parameters

Paramete:

Mandatory parameter

Description

apikey

API key. You can get a key in the developer's dashboard.

lang

The API lets you display maps that are localized in various languages with allowances for the differences in specific countries. To control localization, pass the locale in the HTTP request.

The locale is set in the lang parameter:

lang=language_region
  • language — The two-letter language code. Specified in ISO 639-1 format. Sets the language for objects on the map (toponyms and controls).

  • region — The two-letter country code. Specified in ISO 3166-1 format. Determines regional settings such as measurement units (for indicating distances between objects or driving speeds on a route).

    Note

    For the regions RU, UA, and TR, distance is shown in kilometers. For US, distance is shown in miles.

The following locales are currently supported:

  • lang=tr_TR
  • lang=en_US (distance in miles)
  • lang=en_RU
  • lang=ru_RU
  • lang=ru_UA
  • lang=uk_UA

Note

In early versions of the API, the locale was specified after a dash. This notation is no longer recommended for use, but for backward compatibility, the locales ru-RU, tr-TR, en-US, and uk-UA are considered equivalent to ru_RU, tr_TR, en_US, and uk_UA.

suggest_apikey

Key Geosuggest API. You can get a key in the developer's dashboard.

Warning

To use a suggest in JS API:

  1. Get the key for the suggest in the developer's dashboard.
  2. Specify it when connecting the JS API in the format https://api-maps.yandex.ru/2.1/?lang=ru_RU&apikey=<your key for JS API>&suggest_apikey=<your key for Suggest API>.

coordorder

The order for setting geographical coordinates in API functions that accept longitude-latitude input (for example, Placemark).

Possible values:

  • latlong— [latitude, longitude] — used by default.
  • longlat— [longitude, latitude].

Default value: latlong.

load

List of modules to load.

Module names are comma-separated. For example, load=Map,Placemark,map.addon.balloon.

Components can also be loaded on demand, using the require function.

Default value: package.full.

mode

API loading mode.

The API code can be loaded in packed format to minimize traffic and browser execution time (mode=release), or as source code (mode=debug).

Loading the source code is useful for debugging JavaScript components, since the code of all the loaded components can be viewed. In addition, this mode outputs error messages and exceptions to the console. When the packed format is loaded, these messages are not output.

Default value: release.

csp

Enables CSP mode. Accepts the value "true". For more information, see Enabling the API when using CSP.

ns

The namespace that the API programming components are localized in.

By default, all the objects belong to the ymaps namespace (for example, ymaps.Map). If you specify ns=myNameSpace when loading the API, these objects will be accessible as myNameSpace.Map.

Using a namespace helps avoid crossovers between the names of functions and various programming components used in the API and in user code or other third-party code.

You can set an empty ns value. In this case, the API will not create objects in the global viewport, and access to API functionality will only be given to the function specified in the onload parameter.

Default value: ymaps.

onload

Name of the function that must be called after the API components are loaded and ready to use (callback). The namespace object with API functionality will be passed to this function as an argument.

Nested namespaces may be used:

onload=myfunction

onload=myapp.dosmth

A usage example is provided in the table below.

onerror

The name of the callback function that will be called if an error occurs when loading the API. This function will be passed an object containing information about the error, in the form of an argument.

* Only for commercial versions of the API.

Loading the API on a condition

You can also use the modules.require function to enable separate API components, which is convenient when loading must depend on certain conditions.

<script src="https://api-maps.yandex.ru/2.1/?apikey=Your API key&load=Map&lang=en_US"
 type="text/javascript"></script>
<script type="text/javascript">
  ymaps.ready(function () {
    var map = new ymaps.Map("map", {
          center: [55.76, 37.64], 
          zoom: 10
        });

    if (map) {
      **ymaps.modules.require**(['Placemark', 'Circle'], function (Placemark, Circle) {
        var placemark = new **Placemark**([55.37, 35.45]);
      });
    }
  });
</script>

API readiness

Yandex.Map API components are always loaded asynchronously. This is true even if the script tag is used for enabling the API and no other special actions are performed for asynchronous loading.

In order to be sure that the components are loaded and ready for use, use the ready function or the onload loading parameter.

Using the ready() function

Using the onload loading parameter

<script src="https://...?apikey=Your API key&load=package.full&lang=ru_RU></script>
<script type="text/javascript">
  var myMap;
  ymaps.ready(function () {
    myMap = new ymaps.Map("YMapsID", {
      center: [55.76, 37.64],
      zoom: 10
    });
  ...
  });
</script>

<div id="YMapsID" style="width: 450px; height: 350px;"></div>
// Creating the map's div container
<div id="YMapsID" style="width: 450px; height: 350px;"></div>

<script type="text/javascript">
    var myMap;
    function init (ymaps) {
        myMap = new ymaps.Map("YMapsID", {
            center: [55.87, 37.66],
            zoom: 10
        });
        ...
    }
</script>

// The init function will be called 
// immediately after loading the API. 
// When it is executed, the map's 
// div container will be ready.
<script src="https://...?apikey=Your API key&load=package.full&lang=ru_RU&onload=init"><script>

The occurrence of an event for loading the DOM tree or document does not indicate that the API has finished loading. In other words, using event handlers like document.ready, window.onload, jQuery.ready or others does not allow you to determine whether the components are ready for use.

For the map to be initialized, the DOM tree must contain the element that the map is placed in.

The ready function executes its code only after the API components and the document's DOM tree are loaded.

The function passed to the onload parameter is called after the API is loaded, but does not keep track of the DOM tree's readiness. In this case, you must track the availability of the HTML element that the map is placed in. For example, you can use the event handlers that are listed above.

Using the onload parameter lets you initialize the map without waiting for the DOM to be completely formed. This is why this method is the fastest way to load the API.

Enabling the API when using CSP

If your application uses Content Security Policy (CSP), you need to add rules to the policy sets that will allow loading resources from Yandex domains.

Alert

By default, CSP support is disabled in the API. To activate it when enabling the API, pass the parameter csp=true:

https://api-maps.yandex.ru/2.1/?apikey=Your API key&lang=ru_RU&csp=true

The table below shows the rules to add to your policy sets for working with the API. The rules are listed separately for each directive. Note that the ellipsis in examples signifies that the rules necessary for using the API are shown without regard for other rules that the developer may set for the application. If the policy allows loading from any sources for one of the directives (for example, 'img-src *;'), you don't need to set the API rules for this directive.

Directive

Rules to add to the directive

img-src

For the img-src directive, add the following domains to the list of allowed sources:

  • https://*.maps.yandex.net (for loading tiles)
  • api-maps.yandex.ru (for loading cursors, etc.)
  • https://yandex.ru

API images will be loaded from these domains. In addition, some API images are inserted using data:URL, so the img-src directive should also specify the data: protocol.

img-src data: https://*.maps.yandex.net api-maps.yandex.ru ...;

frame-src

The frame-src directive should allow the domain

  • https://api-maps.yandex.ru

This is the source domain for API components that are shown in frames (such as the «Open in Yandex Maps» block):

frame-src https://api-maps.yandex.ru ...;

Note

The frame-src directive is used in CSP version 1.0. In version 2.0, this directive is replaced with child-src. However, some browsers don't support CSP 2.0 yet, so we recommend setting both of these directives in the policy for cross-browser compatibility:

frame-src https://api-maps.yandex.ru ...;
child-src https://api-maps.yandex.ru ...;

script-src

In the script-src directive, add the following domains:

  • https://api-maps.yandex.ru
  • https://suggest-maps.yandex.ru
  • https://*.maps.yandex.net
  • https://yandex.ru

API modules will be loaded from these domains. In addition, we recommend enabling support for 'unsafe-eval' for working with templates in the script-src directive (this is necessary for conditional operators to work).

script-src 'unsafe-eval' https://api-maps.yandex.ru https://suggest-maps.yandex.ru https://*.maps.yandex.net https://yandex.ru ...;

connect-src

For the connect-src directive, allow the domains:

  • https://api-maps.yandex.ru
  • https://suggest-maps.yandex.ru
  • https://*.maps.yandex.net
  • https://yandex.ru
connect-src https://api-maps.yandex.ru https://suggest-maps.yandex.ru https://*.maps.yandex.net https://yandex.ru ...;

style-src

For loading API styles, the style-src directive must specify the blob: protocol.

style-src: blob: ...;

The API will add styles to the page via a element containing the blob URL of the necessary style. If the application can't use blobs, the style-src directive should specify a nonce value generated on the client side so that the API can function correctly. In this case, the API will enable styles via the <style nonce="..."> inline element.

style-src 'nonce-<token>' ...;

The same value should be passed in the "csp" parameter when enabling the API:

https://api-maps.yandex.ru/2.1/?lang=ru_RU&csp[style_nonce]=<token>

Note that the nonce attribute is implemented in CSP 2.0, and is not supported in version 1.0. However, some browsers don't support CSP 2.0 yet, so we recommend using the blob protocol in style-src for cross-browser compatibility.

If the policy is defined incorrectly for one of the API resources, the map (or its objects) will be displayed incorrectly. However, the API doesn't keep track of which resources have an incorrect policy setting. You can use the report-uri directive to get information about which map resources can't be loaded.

The example below shows a policy that sets rules for using the API, along with other rules for the application:

Content-Security-Policy: img-src data: https://*.maps.yandex.net https://yandex.ru
'self'; child-src https://api-maps.yandex.ru; frame-src https://api-maps.yandex.ru;
 script-src 'unsafe-eval' https://api-maps.yandex.ru https://suggest-maps.yandex.ru
 http://*.maps.yandex.net https://yandex.ru 'self'; style-src blob:
 https://cdn.my-styles.ru;

Setting inline styles in templates with CSP enabled

Sometimes you need to set inline styles for DOM elements when working with templates (such as when setting automatic balloon positioning). If CSP mode is disabled in the API, inline styles are set in the standard way, like normal HTML text. For example:

<div style="width: {{options.width}}px;></div>

But if CSP mode is enabled and the policy forbids 'unsafe-inline', this format won't work. To circumvent the ban on inline styles in templates, use one of the following approaches:

  1. Set inline styles using the construction {% style %}:

    <div {% style %}width: {{ options.width }}px;{% endstyle %}></div>
    

    Note

    To avoid making the developer manually insert this construction in existing templates, you can enable backward compatibility for templates. To do this, pass the "csp" parameter with the "data_style" field when enabling the API:

    https://api-maps.yandex.ru/2.1/?apikey=Your API key&lang=en_US&csp[data_style]=true
    

    As a result, the API will automatically replace the standard format (<div style=..) with {% style %}.

    Note that when using the "csp[data_style]" option, performance issues may arise. This is why we don't recommend enabling this option.

  2. Dynamically create styles and use JavaScript to apply them to DOM elements. For more information, see the example in the sandbox.

Module system

The Yandex Maps API was developed using a modular concept. This allows you to configure the API for specific tasks and gives you the ability to regulate the amount of download traffic.

The modules are separate named entities, such as classes, static objects, and functions. A list of API modules is provided in the Reference guide.

By default, enabling the API loads the set of main modules necessary for using the API (package.full).

Note

Some public modules are not in package.full (for example, overlay.Placemark). The API loads these modules when they are actually used. These entities usually do not have a public constructor. They are created by special factories (for example, objects with the router.Route type are created by the router), or by accessing asynchronous storage by key (for example, overlay.storage). Direct instantiation of such objects is not recommended, but the ability to get the direct constructor is provided in the API. To do this, specify the module name explicitly when enabling the API (in the load parameter) or via modules.require.

In order to minimize traffic, only load the modules that are necessary. There are two ways to do this: when initializing the API, or on demand via the modules.require function. These methods are examined in detail below.

Note

When enabling modules, you only need to specify the ones that will be accessed in the code via the ymaps namespace. The module system is designed so that when initializing the main modules, all the data they need is loaded automatically.

The API allows you to add new modules to the module system and redefine existing modules.

Loading modules when enabling the API

The modules to load are set in the HTTP parameter load in the string for enabling the API. You can specify multiple modules by separating them with spaces. By default, the load parameter takes the package.full value, meaning it loads all the main modules that are needed by the API.

<script src="https://api-maps.yandex.ru/2.1/?apikey=Your API key&lang=en_US&**load**=Map,Placemark" type="text/javascript"></script>

The loaded modules will be enabled in the public namespace ymaps.

If additional modules are required for the given modules to work, they will be loaded automatically.

The Sandbox has an example of loading modules via the load parameter.

Loading modules on demand

Sometimes a module needs to be loaded on demand. Use the [{#T}modules.require.md]](../../ref/reference/modules.require.md) function for this purpose:

if (!ymaps.Map) {
    ymaps.**modules.require**(['Map', 'Placemark'], function (Map, Placemark) {
         // Adding the class manually to the global viewport, since this doesn't happen when using the module system's "require" method.
        ymaps.Map = Map;
        var map = new ymaps.Map('map', { 
              center: [55.76, 37.64], 
              zoom: 10    
            }),
            // The Placemark class wasn't added to the public viewport.
            placemark = new Placemark([55.55, 37.00]);
        map.geoObjects.add(placemark);
    })
    /* The placemark won't be created because the Placemark class isn't included in ymaps.
    var newPlacemark = new ymaps.Placemark([55.50, 37.00]); 
    */
}
</script>

Since these modules may require loading additional modules in order to work, the modules.require function supports asynchronous mode. When the data needed by the specified modules is ready, it calls the callback function with the loaded modules.

The Sandbox has an example of loading modules on demand.

Enabling add-ons

Displaying a geo object's balloon and hint is performed using the balloon and hint fields for the GeoObject class. To initialize these fields, you must enable the modules geoObject.addon.balloon and geoObject.addon.hint. If you need to open a balloon or hint that belongs to the map, you need to enable the map.addon.balloon and map.addon.hint modules.

If you need to be able to edit a geo object's geometry, you should enable geoObject.addon.editor.

The Sandbox has an example of enabling add-ons.

Creating custom modules

You can use the API module system to create custom programmatic modules. This is useful when writing large-scale applications based on the Yandex Maps API.

The module is declared using the modules.define method. The Sandbox has an example of declaring and using a custom module.

The module declaration can be made before calling the ymaps.ready handler.

After the module has been declared in the module system, it can be used in an application.

Note

Custom modules are not added automatically in the general namespace with the API modules. A declared module can be accessed via the asynchronous modules.require method, which returns a promise object.

ymaps.modules.require(['PlacemarkButton'])
  .spread(function (PlacemarkButton) {
    myMap.controls.add(new PlacemarkButton('Click to add a placemark'));
});
Next