2011-11-17 102 views
1

嗨有一個城市陣列,並希望創建一個谷歌地圖使用javascript api v3。 當頁面加載地圖時,跳轉到每個標記。另外,地圖變得非常小,即使我已設置的高度和寬度它。這裏是我的代碼生成的地圖谷歌地圖與多個標記從一個PHP陣列

<script> 
var geocoder; 
var map; 
var timeout = 600; 
var address_position = 0; 
var address = [ 
    <?php 
     foreach($cities_in_country as $item) 
     { 
      echo '"'.$item['name'].'",'; 
     }  
    ?>    
    ]; 

    function addMarker(position) 
    { 
     geocoder.geocode({'address': address[position]}, function(results, status) 
     { 
      address_position++; 
      if (address_position < address.length) 
      { 
       setTimeout(function() { addMarker(address_position); }, (timeout)); 
      } 
      if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) 
      { 
       setTimeout(function() { addMarker(position); }, (timeout * 3)); 
      } 
      else if (status == google.maps.GeocoderStatus.OK) 
      { map.setCenter(results[0].geometry.location);     
       var marker = new google.maps.Marker({ 
        position: results[0].geometry.location, 
        map: map,     
        icon:"<?=base_url()?>assets/goo/images/icons/marker.png",        
       });   
      } 
     }); 
    } 


function codeaddress() { 

    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 
    var myOptions = { 
     zoom: 6, 
     center: latlng,  
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}, 
    mapTypeId: google.maps.MapTypeId.ROADMAP,  
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    addMarker(address_position); 


} 

$(document).ready(function() {  
    codeaddress(); 

}); 
</script> 

<div id="map_canvas" style="width: 640px; height: 420px;"></div> 

回答

3

「地圖不斷跳躍到每個標記「。 - 這是因爲您在循環的addMarker函數中調用map.setCenter(results[0].geometry.location);。刪除該行,它會停止重新映射地圖。

此外,你應該改變這一點;有一種危險,如果你超過了查詢限制,那麼你將繼續使用更長的超時時間來調用addMarker。

 if (address_position < address.length) 
     { 
      setTimeout(function() { addMarker(address_position); }, (timeout)); 
     } 
     if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) 
     { 
      setTimeout(function() { addMarker(position); }, (timeout * 3)); 
     } 

也許應該是

if (address_position < address.length) 
{ 
    if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) 
    { 
     setTimeout(function() { addMarker(position); }, (timeout * 3)); 
    } else { 
     setTimeout(function() { addMarker(address_position); }, (timeout)); 
    } 
} 
+0

啊。謝謝你。 – Neil