You must determine the coordinates of the location and display the map according to the specific location. If the location cannot be determined, then the center of the map should be installed in Moscow.

The problem is that ymaps.geolocation.get works asynchronously and cannot create a map with location coordinates.

In short, what I want to do:

  1. Create a variable of current location coordinates: var current_coords = null;
  2. We determine the location coordinates using ymaps.geolocation.get , if the coordinates are not determined, then we return the coordinates of Moscow
  3. Assign the current_coords variable the coordinates obtained in step 2
  4. Create and display a map: var myMap = new ymaps.Map('map', {center: current_coords, zoom: 6});
  5. Add points to the map, polygon-shaped zones, etc.

It turns out that you have to wait until step 2 works out, and only then perform steps 3-5. I can not understand how this can be implemented.

    2 answers 2

    This example shows how to handle location retrieval https://tech.yandex.ru/maps/jsbox/2.1/geolocated_map

    • This is understandable, but then in the function (res){} and function (err){} branch I will describe the same thing - steps 4-5 - Roman69
    • Well, then bring them to the function) If you want to make sure that only after the appearance of geolocation a map appears, then you need to make a function of creating a map and transfer coordinates to it, depending on the results of geolocation. By the way, geolocation has a timeout option, for example, if you want to wait for an answer for a strictly defined time tech.yandex.ru/maps/doc/jsapi/2.1/ref/reference/… - se0ga
    • Making a function is also not an option - you have to write the same function in two branches. You can somehow use promises and Promise.all? - Roman69
    • The function is the same, the values ​​are different. Create a map with these coordinates or create a map with other coordinates. You can create a map before and then install a new center for it when geolocation comes, but this will be a departure from the logic that you described. - se0ga
    • Installing a new center of the map is not an option; you must immediately display the map in the desired geolocation. It seems to have turned out to be done (see above) - Roman69

    It turned out to do this:

     var current_coords = null; // ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ мСстополоТСния ymaps.vow.Promise.all([getGeolocation()]).then(function(res){ myMap = new ymaps.Map('map', { center: res[0], zoom: 6 }); }); /* ΠžΠΏΡ€Π΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚ мСстополоТСния */ function getGeolocation(){ var сoordinates_promise = ymaps.geolocation.get({ provider: 'yandex', mapStateAutoApply: true }).then( function(res){ return res.geoObjects.get(0).geometry.getCoordinates(); } ).catch(function (err){ console.log('Ошибка опрСдСлСния мСстополоТСния'); return [37.61691485505143, 55.7517318022522]; }); return сoordinates_promise; }