Google Maps V3带有中心多个标记和自动缩放的问题

时间:2011-10-16 16:47:27

标签: google-maps zoom google-maps-markers center

我需要知道如何将所有标记居中并自动缩放地图以使其适合我的以下地图。我几天就打破了头来解决问题,请帮助我。

我的代码

<script type="text/javascript">  
  var map;
  var address = new Array();
  //we can also create following array with a for loop
  address[0] = '798 9th Ave, New York, NY';
  address[1] = '42 E 29th St, New York, NY';
  address[2] = '56 W 25th St, New York, NY';
  address[3] = '26 W 21th St, New York, NY';

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

    for (var i=0; i<=address.length; i++) {     
        geocoder.geocode({'address': address[i]}, function(results, status) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({map: map, position: results[0].geometry.location});      
        });
    }   
  }  
</script>

1 个答案:

答案 0 :(得分:6)

<script type="text/javascript">  
  var map;
  var address = new Array();
  //we can also create following array with a for loop
  address[0] = '798 9th Ave, New York, NY';
  address[1] = '42 E 29th St, New York, NY';
  address[2] = '56 W 25th St, New York, NY';
  address[3] = '26 W 21th St, New York, NY';

  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP}
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    //Mod        
    var bounds = new google.maps.LatLngBounds();

    for (var i=0; i<=address.length; i++) {     
        geocoder.geocode({'address': address[i]}, function(results, status) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({map: map, position: results[0].geometry.location});  
            //Mod
            bounds.extend(marker.getPosition());
        });
    } 
    //Mod
    map.fitBounds(bounds);
  }  
</script>