Trying to get an array of view coordinates

[ [55.75, 37.50], [55.75, 37.71], [55.70, 37.70] ] 

Code

 var coords = []; for ( var i = 0; i < addresses.length; i++ ) { ymaps.geocode(addresses[i], {results: 1 }).then(function (res) { console.log(res.geoObjects.get(0).geometry.getCoordinates()); // ok coords.push(res.geoObjects.get(0).geometry.getCoordinates()); }); } console.log(coords); // empty 

At the output, I get an empty array: (

  • Because console.log(coords); runs before geocode calls complete. Read about asynchrony and promises - Alexey Ten
  • Yes, I read already. If I knew how to solve this problem, I would not write here, it is logical? So your answer is at least incorrect. - Guest
  • This question is asked several times a week. ru.stackoverflow.com/a/487996/190728 here, for example, one of the solutions to your problem. - Alexey Ten
  • Well, thanks and on it. The truth is not quite clear how this. Stackoverflow.com/questions/487992 ... can help solve my problem. - Guest

1 answer 1

multi-geocoder implementation:

https://github.com/deflexor/ymaps/blob/patch-1/multi-geocoder.js

 * Класс для гСокодирования списка адрСсов ΠΈΠ»ΠΈ ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚. * @class * @name MultiGeocoder * @param {Object} [options={}] Π”Π΅Ρ„ΠΎΠ»Ρ‚Π½Ρ‹Π΅ ΠΎΠΏΡ†ΠΈΠΈ ΠΌΡƒΠ»ΡŒΡ‚ΠΈΠ³Π΅ΠΎΠΊΠΎΠ΄Π΅Ρ€Π°. */ function MultiGeocoder(options) { this._options = options || {}; } /** * Ѐункция мноТСствСннСого гСокодирования. * @function * @requires ymaps.util.extend * @see http://api.yandex.ru/maps/doc/jsapi/2.x/ref/reference/util.extend.xml * @requires ymaps.util.Promise * @see http://api.yandex.ru/maps/doc/jsapi/2.x/ref/reference/util.Promise.xml * @name MultiGeocoder.geocode * @param {Array} requests Массив строк-ΠΈΠΌΠ΅Π½ Ρ‚ΠΎΠΏΠΎΠ½ΠΈΠΌΠΎΠ² ΠΈ/ΠΈΠ»ΠΈ Π³Π΅ΠΎΠΌΠ΅Ρ‚Ρ€ΠΈΠΉ Ρ‚ΠΎΡ‡Π΅ΠΊ (ΠΎΠ±Ρ€Π°Ρ‚Π½ΠΎΠ΅ Π³Π΅ΠΎΠΊΠΎΠ΄ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅) * @returns {Object} Как ΠΈ Π² ΠΎΠ±Ρ‹Ρ‡Π½ΠΎΠΌ Π³Π΅ΠΎΠΊΠΎΠ΄Π΅Ρ€Π΅, Π²Π΅Ρ€Π½Π΅ΠΌ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚-ΠΎΠ±Π΅Ρ‰Π°Π½ΠΈΠ΅. */ MultiGeocoder.prototype.geocode = function (requests, options) { var self = this, size = requests.length, defer = new ymaps.vow.defer(), geoObjects = new ymaps.Collection(); requests.forEach(function (request, index) { ymaps.geocode(request, ymaps.util.extend({}, self._options, options)) .then( function (response) { var geoObject = response.geoObjects.get(0); geoObject && geoObjects.add(geoObject, index); --size || defer.resolve({ geoObjects : geoObjects }); }, function (err) { defer.reject(err); } ); }); return defer.promise(); };