2012-06-29 105 views
1

我有几个标记,我检索并希望将地图居中。 是的,我看过所有其他的答案,但它似乎并没有为我工作: Google Map API v3 — set bounds and center谷歌地图API v3 - fitBounds中心只有一个标记

JS:

geocoder.geocode({'address': loc}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var markerBounds = new google.maps.LatLngBounds(); 
      var coordinate = results[0].geometry.location; 
      var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44)); 

      //create the marker 
      var marker = new google.maps.Marker({ 
       map: map, 
       position: coordinate, 
       visible: true, 
       id: type, 
       shadow: shadow, 
       icon: icon 
      }); 
      markerBounds.extend(coordinate); 
      map.fitBounds(markerBounds); 
     } 
} 

回答

1

您的代码始终在呼唤fitBounds只有一个点的的LatLngBounds ,最后一个标记... 如果您多次调用该函数,每次调用它时,都会将最后一个标记的fitBounds。 您可以在geocoder.geocode函数外定义markerBounds变量,因此它会保留它的值。

var markerBounds = new google.maps.LatLngBounds(); 
geocoder.geocode({'address': loc}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var coordinate = results[0].geometry.location; 
      var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44)); 

      //create the marker 
      var marker = new google.maps.Marker({ 
       map: map, 
       position: coordinate, 
       visible: true, 
       id: type, 
       shadow: shadow, 
       icon: icon 
      }); 
      markerBounds.extend(coordinate); 
      map.fitBounds(markerBounds); 
     } 
} 

现在,markerBounds被初始化一次,并用每个新标记进行扩展。

+0

yesssssssssir +1 –

+0

是的,我认为是很好,我试图确定有markerBounds(和所有其他可能的地方,你可以把它)。 但我再次尝试了你的方式,但仍然只是像你说的最后一个中心.. – meneerfab

+1

嗯,这很奇怪..如果它在一个地方,它只会执行一次它应该工作。您发布的代码上面是什么? – iwiznia

0

其实,你可以在输出中的边界的什么COORDS是商店,可记录:

console.log("mapFitBounds:"+bounds);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

然后就是检查你的日志在Chrome的控制台。你会知道这个问题,因为我发现它有两个重复的坐标,然后针对这个问题。