jun_dev
@jun_dev
Frontend-developer

Как установить координаты по умолчанию, если запрещён доступ к геоданным в Яндекс API?

Если запрещён доступ к геоданным, центр устанавливается по провайдеру, а нужно установить центр что указывал при создании карты.

Подскажите, как это сделать?

Мой код
if (document.getElementById('map')) {
    fetch('./addresses.json')
    .then(response => response.json())
    .then((adresses) => {

        ymaps.ready(function () {

            let imgUrl = './img/dist/icons/'; // путь к иконкам меток

            ymaps.geolocation.get().then(function (result) {

                result.geoObjects.options.set(label('label-user')) // Определяем метку пользователя

                // Создаём карту
                let myMap = new ymaps.Map('map', {
                    center: [ 51.128207, 71.430411 ],
                    zoom: 10,
                    controls: [ 'routeButtonControl', 'geolocationControl', 'zoomControl', 'routeButtonControl' ]
                });

                // Стили меток
                function label(label) {
                    return {
                        iconLayout: "default#imageWithContent",
                        iconImageHref: `${imgUrl}${ label }.svg`,
                        iconImageSize: [ 23, 30 ],
                        iconImageOffset: [ -5, -38 ]
                    }
                }

                // Содержимое Balloon
                function balloonContent(item) {
                    return `<div class='balloon-content'>
                                   ...
                                </div>`
                }

                // Метки сluster
                let myGeoObjects = [];
                for (let item of adresses) {
                    myGeoObjects[item.id] = new ymaps.GeoObject({
                        geometry: {
                            type: "Point",
                            coordinates: [ item.lat, item.long ]
                        },
                        properties: {
                            clusterCaption: `${ item.title }`, // Description (Optional. If clusterDisableClickZoom: true),
                            balloonContentBody: balloonContent(item),
                        },
                    }, item.point <= 3 ? label('label-red') : label('label'));
                }

                // Стили сluster
                let myClusterer = new ymaps.Clusterer({
                    // Custom cluster icon (Optional)
                    clusterIcons: [
                        //for clusters containing up to 10 items
                        {
                            href: `${imgUrl}claster-min.svg`,
                            size: [ 40, 40 ],
                            offset: [ -20, -20 ]
                        }, //clusters containing more than 10 items
                        {
                            href: `${imgUrl}claster-max.svg`,
                            size: [ 60, 60 ],
                            offset: [ -30, -30 ]
                        }
                    ],
                    clusterNumbers: [ 10 ], // Max. cluster size = 10
                    //clusterIconContentLayout: null, // Numbers (Optional)
                    clusterDisableClickZoom: false, //Popup - list points (true/false)
                });

                // Построение маршрута
                let map = document.querySelector('#map');
                map.addEventListener('click', ({ target }) => {
                    if (target.className === 'baloon-button') {
                        let control = myMap.controls.get('routeButtonControl');
                        control.routePanel.state.set({
                            fromEnabled: false,
                            to: target.dataset.coordinates
                        })
                        control.routePanel.geolocate('from'); // departure coordinates (using geolocation).
                        control.state.set('expanded', true); // Open the route panel
                        setTimeout(() => {
                            control.state.set('expanded', false);
                        }, 3000)

                    }
                });

                /* Render -----------------------------
                1. Sets the center and zoom factor of the map.
                2. Location label (Optional)
                3. Cluster labels
                ---------------------------------------*/
                myMap.setCenter(result.geoObjects.get(0).geometry.getCoordinates(), 10 /*zoom*/, { duration: 100 });
                myMap.geoObjects.add(result.geoObjects);
                myMap.geoObjects.add(myClusterer.add(myGeoObjects));
            });

        });
    })
}
  • Вопрос задан
  • 115 просмотров
Решения вопроса 1
jun_dev
@jun_dev Автор вопроса
Frontend-developer
Решил вопрос след. образом:

...
             // Render -----------------------------
                function defineLocationCoordinates() {
                    myMap.setCenter(result.geoObjects.get(0).geometry.getCoordinates(), 10, { duration: 100 });
                }

                function defineDefaultCoordinates() {
                    myMap.setCenter( [ 51.128207, 71.430411 ], 10);
                }

                if (!navigator.geolocation) {
                    defineDefaultCoordinates();
                } else {
                    navigator.geolocation.getCurrentPosition(defineLocationCoordinates, defineDefaultCoordinates);
                }


                myMap.geoObjects.add(result.geoObjects);
                myMap.geoObjects.add(myClusterer.add(myGeoObjects));
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы