B
B
bimka2022-04-03 18:35:21
JavaScript
bimka, 2022-04-03 18:35:21

How to pass coords variable in Yandex map?

Yandex.Map is used, where the user clicks on the map and the address is returned to him.
For further purposes, we also need the coordinates of the point from the coords variable of the js file:.

ymaps.ready(init);

function init() {
    var myPlacemark,
        myMap = new ymaps.Map('map', {
            center: [55.753994, 37.622093],
            zoom: 13
        }, {
            searchControlProvider: 'yandex#search'
        });

    // Слушаем клик на карте.
    myMap.events.add('click', function (e) {
        var coords = e.get('coords');

        // Если метка уже создана – просто передвигаем ее.
        if (myPlacemark) {
            myPlacemark.geometry.setCoordinates(coords);
        }
        // Если нет – создаем.
        else {
            myPlacemark = createPlacemark(coords);
            myMap.geoObjects.add(myPlacemark);
            // Слушаем событие окончания перетаскивания на метке.
            myPlacemark.events.add('dragend', function () {
                getAddress(myPlacemark.geometry.getCoordinates());
            });
        }
        getAddress(coords);
    });

    // Создание метки.
    function createPlacemark(coords) {
        return new ymaps.Placemark(coords, {
            iconCaption: 'поиск...'
        }, {
            preset: 'islands#violetDotIconWithCaption',
            draggable: true
        });
    }

    // Определяем адрес по координатам (обратное геокодирование).
    function getAddress(coords) {
        myPlacemark.properties.set('iconCaption', 'поиск...');
        ymaps.geocode(coords).then(function (res) {
            var firstGeoObject = res.geoObjects.get(0);

            myPlacemark.properties
                .set({
                    // Формируем строку с данными об объекте.
                    iconCaption: [
                        // Название населенного пункта или вышестоящее административно-территориальное образование.
                        firstGeoObject.getLocalities().length ? firstGeoObject.getLocalities() : firstGeoObject.getAdministrativeAreas(),
                        // Получаем путь до топонима, если метод вернул null, запрашиваем наименование здания.
                        firstGeoObject.getThoroughfare() || firstGeoObject.getPremise()
                    ].filter(Boolean).join(', '),
                    // В качестве контента балуна задаем строку с адресом объекта.
                    balloonContent: firstGeoObject.getAddressLine()
                });
                
                
            // подтвердим адрес пользователя: улица и дом 
            if (window.confirm("Ваш адрес " + firstGeoObject.getThoroughfare() + ", " + firstGeoObject.getPremiseNumber() + "?")) {   
                // выводим полученный адрес обратно в html документ
                document.getElementById("address_confirm").innerHTML = firstGeoObject.getThoroughfare() + ", " + firstGeoObject.getPremiseNumber()
                document.getElementById("adress_box").style.visibility = 'visible';

                // поместим координаты адреса в невидимый блок
                document.getElementById("hidden_coords").innerHTML = coords;
                
            }
            
        });
    }
}

because the coords variable has a scope only inside its function, I can't figure out how its value can be passed to another third-party script.
So far, I only came up with the idea of ​​creating a hidden block in the html file, passing data to the coords variable there and taking values ​​from this block for a third-party script.
<script>        
        document.getElementById("address_confirm").addEventListener("DOMSubtreeModified", function() {
            responseCoords()
            let ola = document.getElementById("hidden_coords");
            alert(ola.innerHTML[0]);
        });
    </script>

These terrible crutches give me peace. How to remove them? How to do it gracefully?
I thought about getting coordinates from a GET request to Yandex.maps, but I can't extract data from the received json file.
The JSON file looks like this:

/**/id_164899910928934596076({"status":"success","data":{"type":"FeatureCollection","properties":{"ResponseMetaData":{"SearchResponse":{ "found": 9, "context": "ZAAAAAgAEAAaKAoSCQAAAAAAkHZAEQAAAAAAoGZAEhIJAAAAAAAA8L8RAAAAAAAA8L8iAQAoyAE4AED + ////////// 8BSAFiCm1heGFkdj0yMDBqAJ0BzcxMPaABAKgBAOoBAPIBAPgBAIICAIoCAJICAJoCAA ==", "display": "single", "boundedBy": ,"Point":{"type":"Point","

I already see the coordinates I need: 55.747120012826855,37.596858777587904, but I can’t imagine how to extract them.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2022-04-03
@bimka

Get a variable not with a local scope.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question