Google使用php数组中的多个标记进行映射

时间:2011-11-17 15:13:16

标签: google-maps-api-3

您有一系列城市,并希望使用javascript api v3创建一个谷歌地图。 当页面加载时,地图会一直跳到每个标记。即使我已经设置了它的高度和宽度,地图也变得非常小。这是我生成地图的代码

<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>

1 个答案:

答案 0 :(得分: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));
    }
}