2010-08-19 37 views

回答

70

正如其他答案建議,fitBounds()方法應該做的伎倆。

請看下面的例子,這將在東北美國產生10個隨機點,並應用fitBounds()方法:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps LatLngBounds.extend() Demo</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <div id="map" style="width: 400px; height: 300px;"></div> 

    <script type="text/javascript"> 

    var map = new google.maps.Map(document.getElementById('map'), { 
    mapTypeId: google.maps.MapTypeId.TERRAIN 
    }); 

    var markerBounds = new google.maps.LatLngBounds(); 

    var randomPoint, i; 

    for (i = 0; i < 10; i++) { 
    // Generate 10 random points within North East USA 
    randomPoint = new google.maps.LatLng(39.00 + (Math.random() - 0.5) * 20, 
              -77.00 + (Math.random() - 0.5) * 20); 

    // Draw a marker for each random point 
    new google.maps.Marker({ 
     position: randomPoint, 
     map: map 
    }); 

    // Extend markerBounds with each random point. 
    markerBounds.extend(randomPoint); 
    } 

    // At the end markerBounds will be the smallest bounding box to contain 
    // our 10 random points 

    // Finally we can call the Map.fitBounds() method to set the map to fit 
    // our markerBounds 
    map.fitBounds(markerBounds); 

    </script> 
</body> 
</html> 

刷新這個例子很多次,沒有標記過那張視口外:

fitBounds demo

+1

之後是必要的謝謝大家,這確實是我正在尋找的東西! – Calou 2010-08-19 12:28:51

+0

感謝您對您的代碼發表評論。非常非常有用。 – MEM 2014-05-13 15:47:24

6

這裏是這樣的:

map.fitBounds(bounds); 
map.setCenter(bounds.getCenter()); 

界限是座標(標記)的陣列。每次當你放置標記做類似的事情:

bounds.extend(currLatLng); 
+3

我不認爲setCenter在fitBounds – GilShalit 2010-12-21 09:24:11

0

計算正確的縮放顯示所有的標記是不平凡的。但是有一個功能:GMap.fitBounds() - 您定義了一個界限(例如,所有標記座標中最極端的點),並相應地設置地圖。見例如fitbounds() in Google maps api V3 does not fit bounds(答案!)就是一個很好的例子。

0

中心變焦取決於單標記

var myCenter=new google.maps.LatLng(38.8106813,-89.9600172); 
var map; 
var marker; 
var mapProp; 
function initialize() 
{ 
    mapProp = { 
     center:myCenter, 
     zoom:8, 
     mapTypeId:google.maps.MapTypeId.ROADMAP 
    }; 

    map=new google.maps.Map(document.getElementById("map"),mapProp); 

    marker=new google.maps.Marker({ 
     position:myCenter, 
     animation:google.maps.Animation.BOUNCE, 
     title:"400 St. Louis Street Edwardsville, IL 62025" 
    }); 

    marker.setMap(map); 
    google.maps.event.addListener(map, "zoom_changed", function() { 
     map.setCenter(myCenter); 
    }); 
} 

google.maps.event.addDomListener(window, 'load', initialize);