B
B
Berkutman2020-02-23 17:51:33
JavaScript
Berkutman, 2020-02-23 17:51:33

How to dynamically create markers on Google Maps API from array after processing by GeoCoder?

The task is to dynamically add markers on the map after processing the array by the geocoder at the address, in the future, instead of the array, I will take data from the database. Tell me how to implement it, while from the Google documentation I figured out how to do the following, but even everything is bad.

<!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>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-02-23
@Berkutman

CodeAddress function declaration - remove the loop; pass the address as a parameter to the function itself:

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);
    }
  });
}

In initMap iterate over the array of addresses, call codeAddress for each:
address.forEach(n => codeAddress(n, geocoder, map));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question