2012-04-10 39 views
1

我有一个包含多个位置的地图。这些位置在运行时间根据显示的页面确定(它们是我们经销商的位置,因此它们根据经销商编号而有所不同(标记显示正常,但现在我想将地图居中以便缩放为包括所有标记,并根据所显示的标记中心如何做到这一点现在,缩放和中心手动设置这里是我到目前为止的代码:?如何在Google Maps API v3中设置点阵列的中心

<script type="text/javascript"> 
    function initialize() { 
    var locations = [ 
     <?php 
      $loc = ''; 
      $i = 1; 
      foreach ($coordinates as $c) { 
       $loc .= '["' . $c->company . '", ' . $c->latitude . ', ' . $c->longitude . '], '; 
      $i++; 
      } 
      echo substr($loc, 0, -2); 
     ?> 
    ]; 

    var map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 10, 
     center: new google.maps.LatLng(-33.92, 151.25), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    var infowindow = new google.maps.InfoWindow(); 

    var marker, i; 

    for (i = 0; i < locations.length; i++) { 
     marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
     map: map 
     }); 

     google.maps.event.addListener(marker, 'click', (function(marker, i) { 
     return function() { 
      infowindow.setContent(locations[i][0]); 
      infowindow.open(map, marker); 
     } 
     })(marker, i)); 
    } 
    } 

    google.maps.event.addDomListener(window, 'load', initialize); 
    </script> 

回答

6

创建google.maps.LatLngBounds对象,其中包含所有标记“位置,然后用fitBounds方法google.maps.Map对象:

var bounds = new google.maps.LatLngBounds(); 
for (i = 0; i < locations.length; i++) { 
    marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
    map: map 
    }); 
    //Extends bounds to contain marker position 
    bounds.extend(marker.getPosition()); 
    ..... 
} 

map.fitBounds(bounds); 
+0

我得到在Firebug这个错误:Invali d值为

:((1,180),(-1,-180)) – sehummel 2012-04-10 18:33:28

+0

确保所有标记的位置都是有效的LatLng对象,并且bounds有效LatLngBounds对象具有2 LatLng对象(东北,西南GPS坐标) – Engineer 2012-04-10 19:00:07

+0

先生伟大的答案..谢谢很多..他解决了我的问题...伟大的 – 2014-10-29 10:46:04

相关问题