P
P
Pavel Sidorov2020-10-10 21:39:13
JavaScript
Pavel Sidorov, 2020-10-10 21:39:13

How to bind a location button to your html element (Yandex maps api)?

Good day!
Actually on the Yandex map there is a location button. I want to bind a button to my html element and determine the location on click.

Tell me how to do it? There is a method for automatically detecting when loading a map, but it doesn't work very well. Need a click.

ymaps.ready(init);

function init() {
    var geolocation = ymaps.geolocation,
        myMap = new ymaps.Map('map', {
            center: [55.77036255174332, 38.20846108398434],
            zoom: 9,
            controls: ['default']
        }, 
        {
            searchControlProvider: 'yandex#search'
        });

    geolocation.get({
        provider: 'browser',
        mapStateAutoApply: true
    }).then(function (result) {
        // Синим цветом пометим положение, полученное через браузер.
        // Если браузер не поддерживает эту функциональность, метка не будет добавлена на карту.
        result.geoObjects.options.set('preset', 'islands#blueCircleIcon');
        myMap.geoObjects.add(result.geoObjects);
    });
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Sidorov, 2020-10-11
@pavel__sidorov

<div class="map_btn" id="geo">Определить местоположение</div>

var a = document.getElementById('geo');

a.onclick = function() {
    geolocation.get({
    mapStateAutoApply: true
    })
    .then(
    function(result) {
    // Получение местоположения пользователя.
    var userAddress = result.geoObjects.get(0).properties.get('text');
    var userCoodinates = result.geoObjects.get(0).geometry.getCoordinates();
    result.geoObjects.get(0).properties.set({
    balloonContentBody: 'Адрес: ' + userAddress +
    '<br/>Координаты:' + userCoodinates
    });
    myMap.geoObjects.add(result.geoObjects)
    },
    function(err) {
    console.log('Ошибка: ' + err)
    }
    );
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question