PHP 循环中的多个 Google 地图,带有 JavaScript 和引用 ID


multiple google maps in php loop with javascript and reference id

我尝试为php循环中的所有项目生成映射。

.html:

<div class="container main-content">
  <!-- echo out the system feedback (error and success messages) -->
  <?php $this->renderFeedbackMessages(); ?>
  <div class="row">
    <div class="col-md-12">
        <h2>Event Overview</h2>
        <hr>
    </div>
  </div>
  <div class="row">
    <div class="col-md-8 col-md-pull-3">
        <?php
          if ($this->events) {
            foreach($this->events as $key => $value) {
            echo 
            '
              <div class="panel panel-default">
                <div class="panel-heading">
                  <h3 class="panel-title clearfix">
                  <b>' . htmlentities($value->event_name) . '</b> <div class="pull-right">' . htmlentities(date("d.m.y", $value->event_start_timestamp)) . ' - ' . htmlentities(date("d.m.y", $value->event_end_timestamp)) . '</div>
                  </h3>
                </div>
                <div class="panel-body">
                  <div id="map-canvas-' . htmlentities($value->event_id) . '" onload="renderMap(' . htmlentities($value->event_id) . ', ' . htmlentities($value->google_reference_id) . ')"></div>
                </div>
              </div>
            ';
            }
          }
        ?>
    </div>
  </div>
</div>
<!-- Google API Places -->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>

JS脚本:

<script>
  function renderMap(event_id, google_reference_id) {
    var map_settings = <?php echo json_encode($this->events); ?>;
    var request = {
      reference: google_reference_id
    };
    var map = new google.maps.Map(document.getElementById('map-canvas-'+ event_id));
    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.getDetails(request, function(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });
        if (place.geometry.viewport) {
          map.fitBounds(place.geometry.viewport);
        } else {
          map.setCenter(place.geometry.location);
          map.setZoom(15);
        }
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
      }
    });
  }
</script>

JS在同一个php文件中,为了更好地理解,将其分开。是否有在 php 循环中生成映射的选项?唯一画布 id 中的数字有问题吗?我有一个带有硬编码引用的工作解决方案,它仅适用于 document.getElementById 的没有数字的字符串。

ID 中的数字没有问题

div 没有onload事件,函数永远不会被调用。

可能的解决方案:

window.onload = function(){
  var maps = document.querySelectorAll('div[id^="map-canvas-"]');
  for(var i  =0; i < maps.length; ++i ){
    maps[i].onload();
  }
}