谷歌地图。使用PHP变量以有效的方式创建多个infoWindow

时间:2014-07-16 08:58:40

标签: javascript php google-maps

我有很多联系方式。

ES:

<?php
$contactName1 = "Contact name number 1";
$contactName2 = "Contact name number 2";
....
?>

我想在Javascript中传递这些变量并以有效的方式创建它们的相对infoWindow。现在我的代码是:

  <script type="text/javascript">
      var initialize = function() {

      var latlng = new google.maps.LatLng(45.0000, 9.0000);
      var marker1pos = new google.maps.LatLng(45.1111, 9.1111);
      var marker2pos = new google.maps.LatLng(46.2222, 9.2222);

      var map = new google.maps.Map(document.getElementById('mappa'), options);
      map.setOptions({styles: stylesArray });

      var marker1 = new google.maps.Marker({position: marker1pos, map: map, flat: true});
      var marker2 = new google.maps.Marker({position: marker2pos, map: map, flat: true});

      var content1 = '<div class="infoMap"><h2><?php echo $contactName1; ?></h2></div>';
      var infowindow1 = new google.maps.InfoWindow({content: content1});
      google.maps.event.addListener(marker1, 'click', function() { infowindow1.open(map,marker1); });

      var content2 = '<div class="infoMap"><h2><?php echo $contactName2; ?></h2></div>';
      var infowindow2 = new google.maps.InfoWindow({content: content2});
      google.maps.event.addListener(marker2, 'click', function() { infowindow2.open(map,marker2); });

      }
      window.onload = initialize;
  </script>

当联系人数量很大时,编写和维护代码变得困难。

你知道有效的方法吗?也许像PHP中的foreach这样的声明......

提前谢谢大家!

的Alessandro

3 个答案:

答案 0 :(得分:1)

使用数组而不是单个vars:

$contactName1
$contactName2

$contactNames[0]
$contactNames[1]

实施例

<?php foreach ($contactNames as $index => $contactName): ?>
var marker<?php echo $index; ?>pos = new google.maps.LatLng(45.1111, 9.1111);
var marker<?php echo $index; ?> = new google.maps.Marker({position: marker<?php echo $index; ?>pos, map: map, flat: true});
<!-------->
<?php endforeach; ?>

答案 1 :(得分:0)

您可以使用JSON实现。 将jSON数据传递给javascript后,您可以轻松访问它。

<script type="text/javascript">
      var initialize = function() {

      <?php  
           //generate json object
           $jsonObj = ...
           echo "var javascript_json_object=".jsonObj;
      ?>
      //use javascript to access the javascript_json_object variable

      window.onload = initialize;
  </script>

答案 2 :(得分:0)

从php循环db或json

获取联系人
 for($i=1;$i<12;$i++){ 
 $map_contactdetails.="var content1 = '<div class='infoMap'><h2>".$contactName1."</h2></div>';
    var infowindow1 = new google.maps.InfoWindow({content: content1});
    google.maps.event.addListener(marker1, 'click', function() { infowindow1.open(map,marker1); });";    


      }

在内部脚本中你可以调用那个varable

<script type="text/javascript"> 
<?php echo $map_contactdetails; ?>
</script>