Loading API
Description
Work with map is possible only after the code of Maps API is loaded to the browser. There are several ways to download it.
Easy way
First include the Maps API by adding the following code to the head section of the HTML page:
<script src="https://maps.api.2gis.ru/2.0/loader.js?pkg=full"></script>
Then use the DG.then
function, into which we will place the initialization code of the map:
DG.then(function () {
map = DG.map('map', {
center: [54.98, 82.89],
zoom: 13,
});
});
Inside this function adds a handler for of the event of the page loading. This very method was discussed in the Quick start section.
npm
The Maps API can be included via npm:
$ npm i 2gis-maps
After the package is installed, enable it using require
:
var DG = require('2gis-maps');
var map = DG.map('map', {
center: [54.98, 82.89],
zoom: 13,
});
Please note that when you use the npm package, there is no need to use DG.then
.
Download on demand
You can load the Maps API at the very moment when you need the map. To do this, you need to add the lazy=true
parameter to the URL used to include API:
<script src="https://maps.api.2gis.ru/2.0/loader.js?pkg=full&lazy=true"></script>
Then, at the right time (for example, when pressing the button) you must call the DG.then
function:
DG.then(function () {
map = DG.map('map', {
center: [54.98, 82.89],
zoom: 13,
});
});
Connection options
The following are all options that can take the URL of the Maps API loading:
Option | Default | Description |
---|---|---|
pkg |
full |
Package of loadable modules. Currently, 2 packages are supported: full — all API modules; basic — basic functionality (popups, markers, vector objects). |
skin |
dark |
The theme of controls (light or dark). Takes the value light or dark . |
lazy |
false |
If you specify the true value, then the Maps API will load with delay, when you first call DG.then . |
DG.then function
As described earlier, the function DG.then
is responsible for tracking the moment of loading the Maps API and adding handlers for this action. Function parameters:
Function | Returns | Description |
---|---|---|
DG.then( <Function> resolve, <Function> reject ) |
Promise |
Registers API loading handlers. Parameters: resolve is a function triggered in case of a successful loading of the Maps API, reject is a function triggered in case of server errors. |
The call of the DG.then
function at any time after the API loading will be immediately executed by the handler.