Multiple Google Maps with Map field

I am trying to display multiple google maps on one page, and also using the Map field. The data for the locations is on subpages. Im having trouble generating the the javascript because of the way the variable needs to be structured.

I have got this far:

<script type="text/javascript">
var map1, map2;
function initMap() {

    var mapOptions = {
      zoom: <?= c::get('map.defaults.zoom') ?>,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: true,
      fullscreenControl: false
     }
    <?php foreach($page->children() as $location): ?>
    mapOptions.center = new google.maps.LatLng(<?= $location->location()->yaml()['lat']; ?>, <?= $location->location()->yaml()['lng']; ?>);
    map1 = new google.maps.Map(document.getElementById(<?= $location->uid() ?>), mapOptions);
    <?php endforeach ?>
 }
</script>

How can I dynamically change the var, so that it works for any amount of subpages (aka locations):

var map1, map2;

For reference I am basing my code on this article.

Use a counter variable or indexOf().

Ok… thanks… I waited for more typing, but there was none :slight_smile:

I am not sure what you mean. I looked up indexOf() but without some kind of real example in the docs, I don’t really know what to do with it. Could you elaborate please?

$locations = $page->children();
foreach($locations as $location) {
  echo $locations->indexOf($location); // or add +1 if you want to start at 1 (index starts at 0)
}

Thanks. This did the trick…

<script type="text/javascript">
var <?php foreach($locations as $location): ?>map<?= $locations->indexOf($location) ?><?php if($location->is($locations->last())): ?><?php else: ?>,<?php endif ?><?php endforeach ?>;
function drawMap() {
    var mapOptions = {
      zoom: <?= c::get('map.defaults.zoom')?>,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: true,
      fullscreenControl: false
     }

    <?php foreach($locations as $location): ?>
    mapOptions.center = new google.maps.LatLng(<?= $location->location()->yaml()['lat']; ?>, <?= $location->location()->yaml()['lng']; ?>);
    map<?= $locations->indexOf($location) ?> = new google.maps.Map(document.getElementById("<?= $location->uid() ?>"), mapOptions);
    <?php endforeach ?>
 }
</script>