2011-11-17 105 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