A
A
Arseny Sokolov2017-01-18 14:11:59
Yandex maps
Arseny Sokolov, 2017-01-18 14:11:59

How to show custom city on page load?

There is a page on which Yandex.maps are loaded, and they are initialized like this:

$(funcntion(){
    var userCityId = 234 // Это мы узнаем от пользователя или при инициализации приложения, данные берутся из настроек пользователя.
    ymaps.ready(initMap).then(function() {;
        selectUserCity(userCityId);
    });
});

// Инициализируем с городом по-умолчанию
var initMap = function() {
    myMap = new ymaps.Map('map', {
        center: [55.751574, 37.573856],
        zoom: 9,
        controls: ["geolocationControl", "trafficControl", "typeSelector", "zoomControl"]
    });
    myMap.behaviors.disable('scrollZoom');
};

var selectUserCity = function(cityId) {
    $.get('/data/get/cityName/json', {id: cityId}, function (data) {
        // некоторые манипуляции с переменными
        setUserCityAtMap(data.name);
    });
};

// Если вызывать эту функцию после изменения настроек в интерфейсе пользователя, то все отлично отрабатывает.
// А при загрузке страницы не правильно работает.
var setUserCityAtMap = function (cityName) {
    ymaps.geocode(cityName, { result: 1 }).then(function (res) {
        var firstGeoObject = res.geoObjects.get(0),
              bounds = firstGeoObject.properties.get('boundedBy');

        myMap.setBounds(bounds, { checkZoomRange: true });
        myCollection = new ymaps.GeoObjectCollection();
    });
};

Also, if the user changes his city to another or the same one, then everything is displayed correctly on the map, and the same selectUserCity() function is called .
Where am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2017-01-18
@freeExec

Try moving the setUserCityAtMap function to the beginning, before calling it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question