U
U
user_tm2020-01-13 19:32:04
Yandex maps
user_tm, 2020-01-13 19:32:04

How to change the center of Yandex maps by clicking on the button?

Hello! There is a Yandex map with id="map"

<div id="map" style="width: 99%; height: 500px" class="myMap"></div>

and button The task is as follows: the agency has three addresses<button id="btnMap">кнопка </button>
var myCenter0 = [59.893254, 30.331014];
var myCenter1 = [59.890658, 30.318321];
var myCenter2 = [59.894513, 30.320270];
and it is necessary that each time you click on the button with id = "btnMap" the first address is changed to the second, the second to the third, and the third to the first, and so on through the cycle. To do this, I put all three addresses in an array, let arrLatLng = [myCenter0, myCenter1, myCenter2];then created it in a variable i where the value of i is zero and I substitute this value into the arrLatLng array key, and I substitute this key into the values ​​of the center property in the myMap class (center: arrLatLng[i]) looks like This is true:var i = 0;
function init(){
        var myMap = new ymaps.Map("map", {
          center: arrLatLng[i],
          zoom: 17
      });
      }
if you manually change the value of the variable i, then the center changes on the map. And I must say that they helped me solve the same problem, but it was on a google map, here is the link How to change addresses by clicking on one button on the Google map api JavaScript? . I tried to solve by analogy but nothing comes out here is the whole code
ymaps.ready(init);
      var myCenter0 = [59.893254, 30.331014];//адрес № 1
      var myCenter1 = [59.890658, 30.318321];//адрес № 2
      var myCenter2 = [59.894513, 30.320270];//адрес № 3
      let arrLatLng = [myCenter0, myCenter1, myCenter2];//массив из трех адресов (или как правильно центры)

      var i = 0; 

      $("#btnMap").click(function() {// во код который решил задачу на google карте 
        i = (i + 1) % arrLatLng.length;
        myMap.setCenter(arrLatLng[i]);

      });

      function init(){
        var myMap = new ymaps.Map("map", {
          center: arrLatLng[i],//вот в ключ массива подставляется значение переменной i таким образом менятся на карте центр 
          zoom: 17
      });

      }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-01-13
@NeiroNx

To change, you need to have access to the map object from the desired function, if myMap has global visibility, then everything is just setCenter

<button onclick="myMap.setCenter([56.0,55.0],18)">Что там?</button>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question