The task of the 3 points given by the coordinates to choose a point from which the path to the given destination point will be the smallest.

The task is performed by Yandex Map Api.

JS code:

ymaps.ready(function () { var map = new ymaps.Map("map", { center: [55.91765312, 37.80059937], zoom: 16 }), myGeoObject = new ymaps.GeoObject({ geometry: { type: "Point", // тип геометрии - точка coordinates: [55.91764107, 37.80413989] // координаты точки } }), brigades=<?php print_r($brJson)?>, accidentPlace=<?php print_r($dist)?>, lengthOfPathes=new Array(), timeOfPathes=new Array(), arr=new Array(); map.geoObjects.add(myGeoObject); //**Здесь начинаются проблемы** for(var key in brigades){ ymaps.route([brigades[key],accidentPlace]).then( function(route){ arr.push(route.getLength()); }, function(error){ alert('Error'+error.msg); }, ); } arr.push(11.45); arr.push(16); console.log(arr); console.log(arr[2]); }); 

In the for in loop, the array is filled with path lengths, but for some reason, the arr array is displayed in the console in this form:

 (2) [11.45, 16] 0: 11.45 1: 16 2: 467.83 3: 1572.84 4: 1555.48 length: 5 __proto__: Array(0) 

PHP:

 <?php echo 45; $distances=[ [55.91494935, 37.81120928], [55.91984168, 37.81219633], [55.92274545, 37.81472833] ]; $brigade=[ 'kostkinTeam'=>[55.91938593, 37.81674452], 'svodinTeam'=>[55.91207938, 37.81317238], 'msuTeam'=>[55.91765312, 37.80059937], ]; $brJson=json_encode($brigade); $item= mt_rand(0, count($distances)-1); $dist=json_encode($distances[$item]); $distancesJson=json_encode($distances); ?> 

Access to elements 2-4 is not, when I try to access, I get undefiened.

Help me understand what the problem is?

    1 answer 1

    ymaps.route is an asynchronous function. You need to wait until all requests are executed.

     var arr = []; var promises = []; for (var key in brigades) { var routePromise = ymaps.route([brigades[key], accidentPlace]).then( function (route) { arr.push(route.getLength()); }, function (error) { alert('Error' + error.msg); } ); promises.push(routePromise); } ymaps.vow.all(promises).then(function () { console.log(arr); }) 
    • Thanks for the detailed solution! It really helped! - Artyom