1

Есть такой код:

marker.addListener('click', function(e) {
    closeAllInfoWindows();
    infowindow.open(marker.get('map'), marker);
    var geocoder = new google.maps.Geocoder;
    geocoder.geocode({'location': e.latLng}, function(results, status) {
          infowindow.open(marker.get('map'), marker);
          if (status === 'OK') {
            if (results[1]) {
              console.log(results[0].formatted_address)
              console.log(results[0].address_components[0].long_name)
              console.log(results[0].address_components[1].long_name)
              cont  =  infowindow.content
              console.log(cont)
              regex = new RegExp(/<small class=\"grey-500\">(.*?)<\/small>/g)
              cont = cont.replace(regex, 
                                  ('<small class="grey-500">'+
                                   results[0].address_components[1].long_name + ', ' + 
                                   results[0].address_components[0].long_name +
                                   '</small>')
                                  ).toString()
              console.log(cont);
            } else {
              window.alert('No results found');
            }
          } else {
            window.alert('Geocoder failed due to: ' + status);
          }
        });

    closeAllInfoWindows();

    infowindow.setContent(cont);
    infoWindow.setPosition(e.latLng);

    infowindow.close(marker.get('map'), marker);
    infowindow.open(marker.get('map'), marker);
  });

"Почти работает".

То есть адрес в infowindow появляется, и даже правильный... Но... После второго клика. По первому клику после загрузки карты адреса нет вообще, по второму клику повляется, затем запаздывает на каждом из маркеров на 1 клик...

В консольку content для infowindow сыпется правильный.

При этом еще выплёвывает такую ошибку:

InvalidValueError: setContent: not a string; and

А вот то, что логирует cont:

11:04:42.887 map4.html:162 <small class="grey-500"></small>

11:04:42.897 map4.html:162 <small class="grey-500">Красногорский бульвар, 13</small>

Подскажите, в чем тут грабли?

1

1 ответ 1

0

Дело было в асинхронной работе geocoder.

Сделал колбэк, заработало как надо:

 marker.addListener('click', function(e) {

    FindAddr(e.latLng, function(data) {
    regex = new RegExp(/<small class=\"grey-500\">(.*?)<\/small>/g);
    infowindow.setContent(infowindow.content.replace(regex, data.Addr.toString()));
    infoWindow.setPosition(e.latLng);
    infowindow.open(marker.get('map'), marker);
    console.log(data);

    });

  });

}
}

function FindAddr(coodrs, callback)
{
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'location': coodrs }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
        addr = '<small class="grey-500">'+ results[0].address_components[1].long_name + ', ' + results[0].address_components[0].long_name +'</small>'
            callback({ Status: "OK", Addr: addr });
        }
    });
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.