Berkutman
@Berkutman

Как создать динамически маркеры на Google Maps API из массива после обработки GeoCoder?

Задача динамически добавлять маркеры на карте после обработки массива геокодером по адресу, в дальнейшем вместо массива буду брать данные из БД. Подскажите как реализовать, пока из документации гугла сообразил сделать следующее, но чет совсем все плохо.

<!DOCTYPE html>
<html>
  <head>
    <title>Geocoding service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var geocoder;
      var map;
		var address = new Array ('Moscow', 'Kurgan');
		
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
		center: new google.maps.LatLng(61.52401, 105.31875600000001),
		zoom: 3
        });
        geocoder = new google.maps.Geocoder();
        codeAddress(geocoder, map);
      }

for (i=0; i<adress.length; i++) {


      function codeAddress(geocoder, map) {
        geocoder.geocode({'address': adress[i]}, function(results, status) {
          if (status === 'OK') {
            var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location
            });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }
	  };
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API-KEY&callback=initMap">
    </script>
  </body>
</html>
  • Вопрос задан
  • 116 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
Объявление функции codeAddress - уберите цикл; в саму функцию передавайте адрес в качестве параметра:

function codeAddress(address, geocoder, map) {
  geocoder.geocode({ address }, function(results, status) {
    if (status === 'OK') {
      new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

В initMap перебирайте массив адресов, для каждого вызывайте codeAddress:

address.forEach(n => codeAddress(n, geocoder, map));
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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