I
I
Igor Pushkarsky2016-01-25 04:42:28
JavaScript
Igor Pushkarsky, 2016-01-25 04:42:28

How to initialize several Yandex maps and adjust the scale from a hidden container?

Hello!

In general, the problem is this, you need to initialize several cards that came from the backend at the same time, some cards are visible immediately on the screen, some are hidden under tabs.

That is, if the first tab works fine, which is currently visible, then the second tab does not want to scale in any way. and shows this and the first one shows this

In fact, both cards are the same for the test, only the container has been replaced.
And I also noticed that the zoom is not perceived by the map at all.

$(document).ready(function(){

    /**
     * Подключаемся к яндекс карты API 2.0
     */

    var maps =[
        {
            'name' : 'addressMap1',
            'center' : [50.443705, 30.530946],
            'zoom' :  10,
            'controls' : ['smallMapDefaultSet'],
            'elemClicking' : 'address__list-item-name-title',
            'arrayObjects' : [
                {
                    id: "235",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 30.563022],
                    name: "м. Старая Деревня",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (812) 748-27-52",
                    timeWork: "9:00–22:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                },
                {
                    id: "236",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 31.563022],
                    name: "м. Старая Деревня2",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (815) 748-27-52",
                    timeWork: "9:00–20:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                }
            ]
        },
        {
            'name' : 'addressMap2',
            'center' : [50.443705, 30.530946],
            'zoom' :  10,
            'controls' : ['smallMapDefaultSet'],
            'elemClicking' : 'address__list-item-name-title',
            'arrayObjects' : [
                {
                    id: "235",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 30.563022],
                    name: "м. Старая Деревня",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (812) 748-27-52",
                    timeWork: "9:00–22:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                },
                {
                    id: "236",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 31.563022],
                    name: "м. Старая Деревня2",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (815) 748-27-52",
                    timeWork: "9:00–20:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                }
            ]
        }
    ] ;

    ymaps.ready(init);

    function init() {

        for (var elem = 0, length = maps.length; elem < length; elem++) {

            /*Приходящие данные*/
            var arrayObjects = maps[elem].arrayObjects;

            /**
             * Создаем экземпляр карты
             * @type {string} addressMap - Id блока куда вставлять карту
             */

            var myMap = [];
            myMap[elem] = new ymaps.Map(maps[elem].name, {
                center: maps[elem].center,
                zoom: maps[elem].zoom,
                controls: maps[elem].controls
            });

            /**
             * Создаем колекцию в которую будем писать гео-элементы на карте
             * @type {ymaps.GeoObjectCollection}
             */
            var collection = new ymaps.GeoObjectCollection();

            /**
             * Сюда запишем все точки на карте
             * @type {Array}
             */
            var placemarks =[];

            for (var i = 0, l = arrayObjects.length; i < l; i++) {

                /*Добавляем на карту колекцию геообъектов*/
                myMap[elem].geoObjects.add(collection);

                //Создаем балун по данным arrayObjects
                placemarks[arrayObjects[i].id] = new ymaps.Placemark(
                    arrayObjects[i].center,
                    {
                        balloonContent: [
                            '<address>',
                            '<strong>'+arrayObjects[i].name+'</strong>',
                            '<br/>',
                            arrayObjects[i].address,
                            '<br/>',
                            arrayObjects[i].phone,
                            '<br/>',
                            arrayObjects[i].timeWork,
                            '<br/>',
                            '<a href="'+arrayObjects[i].timeWork+'">Схема проезда</a>',
                            '</address>'
                        ].join('')
                    },
                    {
                        iconLayout: 'default#image',
                        iconImageHref: arrayObjects[i].iconImageHref,
                        iconImageSize: arrayObjects[i].iconImageSize,
                        iconImageOffset: arrayObjects[i].iconImageOffset
                    }
                );

                /*Добавляем в колекцию наши балуны*/
                collection.add(placemarks[arrayObjects[i].id]);
            }

            /* Подписываемся на событие клика по пункту меню */
            $('.'+maps.elemClicking).click(function(){
                var id = $(this).attr('balloon-id');

                myMap[elem].panTo(placemarks[id].geometry.getCoordinates());
                setTimeout(function () {
                    placemarks[id].balloon.open();
                }, 800);
            });

            /* Выставляем масштаб карты чтобы были видны все группы. */
            myMap[elem].setBounds(myMap[elem].geoObjects.getBounds());

        }
    }

});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Pushkarsky, 2016-01-25
@RainMEN

In general, I seem to have found a solution, but I'm still ready for suggestions.
Regarding the scale, this is due to the fact that the size of the container for the map has display:none; the map considers that the map size is 0, and resets the scale to 0. As a result, I played around with css, everything seems to work.

$(document).ready(function(){

    /*Приходящие данные*/
    var maps =[
        {
            'id' : 1,
            'name' : 'addressMap1',
            'center' : [50.443705, 30.530946],
            'zoom' :  10,
            'controls' : ['smallMapDefaultSet'],
            'elemClicking' : 'address__list-item-name-title',
            'points' : [
                {
                    id: "235",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 30.563022],
                    name: "м. Старая Деревня",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (812) 748-27-52",
                    timeWork: "9:00–22:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                },
                {
                    id: "236",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 31.563022],
                    name: "м. Старая Деревня2",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (815) 748-27-52",
                    timeWork: "9:00–20:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                }
            ]
        },
        {
            'id' : 2,
            'name' : 'addressMap2',
            'center' : [50.443705, 30.530946],
            'zoom' :  10,
            'controls' : ['smallMapDefaultSet'],
            'elemClicking' : 'address__list-item-name-title',
            'points' : [
                {
                    id: "237",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [50.426472, 30.563022],
                    name: "м. Старая Деревня",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (812) 748-27-52",
                    timeWork: "9:00–22:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                },
                {
                    id: "238",
                    iconImageHref: "img/pin-blue.png",
                    iconLayout: "default#image",
                    iconImageSize: [30, 42],
                    center: [55.751574, 37.573856],
                    name: "м. Старая Деревня2",
                    address: "бул. Трудящихся, д.18, к.1",
                    phone: "+7 (815) 748-27-52",
                    timeWork: "9:00–20:00",
                    location: "https://company.yandex.ru/",
                    power: "Откр. 0,5 Тл и закр. 1,5 Тл"
                }
            ]
        }
    ] ;

    var myMap=[];
    var myMapWrap = [];
    var placemarks =[];

    /*Иницилизируем карты*/
    ymaps.ready(init);

    function init() {

        for (var elem = 0, length = maps.length; elem < length; elem++) {

            var points = maps[elem].points;

            var collection = new ymaps.GeoObjectCollection();

            myMap[elem] = new ymaps.Map(maps[elem].name, {
                center: maps[elem].center,
                zoom: maps[elem].zoom,
                controls: maps[elem].controls
            });

            for (var i = 0, l = points.length; i < l; i++) {

                /*Добавляем на карту колекцию геообъектов*/
                myMap[elem].geoObjects.add(collection);

                //Создаем балун по данным points

                placemarks[points[i].id] = new ymaps.Placemark(
                    points[i].center,
                    {
                        balloonContent: [
                            '<address>',
                            '<strong>'+points[i].name+'</strong>',
                            '<br/>',
                            points[i].address,
                            '<br/>',
                            points[i].phone,
                            '<br/>',
                            points[i].timeWork,
                            '<br/>',
                            '<a href="'+points[i].timeWork+'">Схема проезда</a>',
                            '</address>'
                        ].join('')
                    },
                    {
                        iconLayout: 'default#image',
                        iconImageHref: points[i].iconImageHref,
                        iconImageSize: points[i].iconImageSize,
                        iconImageOffset: points[i].iconImageOffset
                    }
                );

                /*Добавляем в колекцию наши балуны*/
                collection.add(placemarks[points[i].id]);
            }

            myMapWrap[elem]=myMap[elem];
            myMapWrap[elem].setBounds(myMapWrap[elem].geoObjects.getBounds());
        }
    }

    $('.'+maps[0].elemClicking).click(function(){
        var id = $(this).attr('balloon-id');
        mapId = $(this).attr('map-id');

        //Центруем карту
        myMapWrap[mapId].panTo(placemarks[id].geometry.getCoordinates());

        //Показываем балун как только отцентруется карта
        setTimeout(function () {
            placemarks[id].balloon.open();
        }, 800);
    });


});

F
forgotten, 2016-01-25
@forgotten

learn.javascript.com/closures

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question