2011-06-14 59 views
1

我想dispaly多個地圖與PHP的循環,但我不能讓它在這裏工作是精簡的代碼...多谷歌地圖用PHP循環

<!doctype html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <title>Google Maps JavaScript API Example</title> 
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAA5iXFaQoABBiRl7JNx5HFuxSa5RD4FXABRIVtLveK1-E6gmai7BR1Y63hhzwAO9ZPoNDgLDBQ_Z6B4Q" type="text/javascript"></script> 


    </head> 
    <body onload="load()" onunload="GUnload()"> 


    <?php 

    if($_POST['select'] == "place"){ 

    $posts = $facebook->api("https://stackoverflow.com/search?q=".urlencode($_POST['search'])."&type=".urlencode($_POST['select'])."&center=".urlencode($_POST['center'])."&distance=".urlencode($_POST['distance']).""); 

    //print_r($posts); 
    $num = "1"; 
    $num2 = "1"; 
    foreach($posts as $v) { 

     foreach($v as $v2) { ?> 

     <div> 
     <script type="text/javascript"> 

    //<![CDATA[ 
    function load() { 
     if (GBrowserIsCompatible()) { 
     var map = new GMap2(document.getElementById("map-<?php echo $num++; ?>")); 
     map.setCenter(new GLatLng(<?php echo $v2['location']['latitude']; ?>, <?php echo $v2['location']['longitude']; ?>), 13); 
     } 
    } 
    //]]> 
     <div id="map-<?php echo $num2++; ?>" style="width: 500px; height: 300px"></div> 
     <p><?php echo $v2['location']['latitude']; ?></p> 
     <p><?php echo $v2['location']['longitude']; ?></p> 
     </div> 
     <?php 

     } 

    } 


    } 

    } 

    ?> 



    </body> 
</html> 

我試圖把javascript的在循環內,但這不起作用。

有沒有人有任何建議,目前它只會顯示循環內的最後一張地圖?

謝謝

回答

2

我可以告訴你爲什麼它不起作用。您每次通過循環重新定義相同的load()函數。所以當文檔加載和load()被調用時,它只是顯示最後的地圖。順便說一句,你也應該使用谷歌地圖V3 API而不是V2,但這是一個不同的話題。

像這樣的東西應該解決這個問題。首先,把這個在<頭>部分:

<script type="text/javascript"> 
var loaders = []; 
function load() { 
    for (var i = 1; i < loaders.length; i++) { 
     loaders[i](); 
    } 
} 
</script> 

然後你的循環改成這樣:

foreach($posts as $v) { 

    foreach($v as $v2) { ?> 

    <div> 
    <script type="text/javascript"> 

//<![CDATA[ 

loaders[<?php echo $num; ?>] = function() { 
    if (GBrowserIsCompatible()) { 
    var map = new GMap2(document.getElementById("map-<?php echo $num++; ?>")); 
    map.setCenter(new GLatLng(<?php echo $v2['location']['latitude']; ?>, <?php echo $v2['location']['longitude']; ?>), 13); 
    } 
}; 
//]]> 
    <div id="map-<?php echo $num2++; ?>" style="width: 500px; height: 300px"></div> 
    <p><?php echo $v2['location']['latitude']; ?></p> 
    <p><?php echo $v2['location']['longitude']; ?></p> 
    </div> 
    <?php 

    } 

}