A
A
Andrew2016-12-26 19:09:08
JavaScript
Andrew, 2016-12-26 19:09:08

How to display google maps in a loop?

Hello.

There is this code:

<div class="contacts col-xs-12">
  <div class="contact-block row">
    <div class="maps col-lg-9" data-addr="<?= $address['address'] ?>"></div>
  </div>
  <div class="contact-block row">
    <div class="maps col-lg-9" data-addr="<?= $address['address'] ?>"></div>
  </div>
</div>


<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap" async defer></script>

<script type="text/javascript">
  var map;
  function initMap() {
    var element = $('.contact-block');
    element.each(function () {
      var self = $(this);
      var container = self.find('.maps');
      var addr = container.data('addr');
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({'address': addr}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          console.info(results);
          var map = new google.maps.Map(container, {
            zoom: 17,
            center: results[0].geometry.location
          });

          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>


I understand that the code is not at all the best, but I didn’t sleep for several days, I don’t have the strength to rewrite it differently. I need something to at least work.

In general, when I run the code, it writes to me in the console that
Uncaught TypeError: Cannot set property 'position' of undefined


Please help me fix it so that the map is displayed in both blocks.

PS $address['address'] contains the address as a string, like "Minsk, Lenina st., house 666", that's why I also use a geocoder that should translate it. console info(results); Returns a norm object.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Arman, 2016-12-26
@ntzch

try
why the first var map;?

N
nosazus, 2017-05-27
@nosazus

Good site. I see the usual parallax, competent and accurate.

M
Maxim Timofeev, 2017-05-28
@webinar

Well, look at the js connected there:
https://fund.cindicator.com/assets/app_f99b034ca79...
Look in the code for the block id, namely "HowItWorks" and you will see how it is implemented.
But in order to receive specific answers, it is advisable to ask specific questions . Because "such a scroll" requires decoding. There's a lot of things done and what exactly you don't understand - it's not clear. They will not tell you step by step in the answers how to make a whole site.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question