Skip to content

Instantly share code, notes, and snippets.

@1234ru
Last active September 30, 2019 16:58
Show Gist options
  • Save 1234ru/abf899a33a29139dd1167edadfd9020a to your computer and use it in GitHub Desktop.
Save 1234ru/abf899a33a29139dd1167edadfd9020a to your computer and use it in GitHub Desktop.
Tiny Yandex.Maps wrapper for on-demand mechanism loading and easy conversion of address to coordinates
/** Обертки для работы с Яндекс.Картами.
* @version 1.2.0.
* см. https://gist.github.com/albburtsev/2ff5478df9d81d35ffb386d1dfb8980a
* */
var ymapTools = {};
/**
* Загрузчик механизма.
*
* Применяется, когда карта на странице нужна не сразу, а по какому-то событию.
*
* Использование:
* ymapTools()
* .load( {apiKey: "ключ Яндекс.Карт"} )
* .then(function() { обычный callback для ymaps.ready() });
*
* @param {object} options
* @param {string|void} options.apiKey API-ключ
* см. http://developer.tech.yandex.ru/
* см. https://tech.yandex.ru/maps/jsapi/doc/2.1/quick-start/index-docpage/
* @return {Promise}
*/
ymapTools.load = function(options) {
options = options || {};
return new Promise( function(resolve, reject) {
if (typeof ymaps !== 'undefined')
ymaps.ready(resolve);
else {
var script = document.createElement('script');
script.src = 'https://api-maps.yandex.ru/2.1/?lang=ru_RU';
if (options.apiKey)
script.src += '&apikey=' + options.apiKey;
script.onload = function() {
ymaps.ready(resolve);
// console.log('Yandex.Maps API loaded. Waiting for ready()...');
};
script.onerror = function() {
var message = 'Loading of "' + this.src + '" script failed.';
var e = new Error(message);
reject(e);
};
document.body.appendChild(script);
// console.log('Yandex.Maps API loading...');
}
} );
} ;
/**
* Преобразование строки адреса в координаты.
*
* Использвание:
* ymapTools.load()
* .then(function() { getCoordinates("адрес").then(function(координаты) { ... }); })
* .catch(function() { callback при ошибке загрузки механизма Яндекс.Карт });
*
* @param {string} address
* @return {Promise}
*/
ymapTools.getCoordinates = function(address) {
return ymaps.geocode(address, { results: 1 })
.then(function (response) {
var coordinates;
var location = response.geoObjects.get(0);
if (location)
coordinates = location.geometry.getCoordinates();
return coordinates;
});
} ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment