2010-03-22 33 views
31

我使用Google API v3中的地理編碼器顯示國家/地區的地圖。我得到了國家推薦的視口,但是當我想將地圖調整到該視口時,它不起作用(請參閱下面的代碼中調用fitBounds函數之前和之後的邊界)。Google地圖api V3中的fitbounds()不適合邊界

我在做什麼錯?

如何將我的地圖的視口設置爲results[0].geometry.viewport

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode(
    {'address': '{{countrycode}}'}, 
    function(results, status) { 
     var bounds = new google.maps.LatLngBounds(); 
     bounds = results[0].geometry.viewport; 
     console.log(bounds);   // ((35.173, -12.524), (45.244, 5.098)) 
     console.log(map.getBounds()); // ((34.628, -14.683), (58.283, 27.503)) 
     map.fitBounds(bounds);    
     console.log(map.getBounds()); // ((25.740, -24.806), (52.442, 17.380)) 
    } 
); 

回答

72

這是因爲fitBounds()需要捕捉到適合使用最大變焦水平可能在地圖畫布視口。另一方面,地理編碼器返回的視口不依賴於地圖畫布的大小,佈局或縮放級別。因此,fitBounds()方法會調整地圖的視口,以便在地圖中心完整地查看傳遞的LatLngBounds

您可能要檢查下面的例子更清晰的示範開始:

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

    <script type="text/javascript"> 
     var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP }; 
     var map = new google.maps.Map(document.getElementById("map"), myOptions); 
     var geocoder = new google.maps.Geocoder(); 

     geocoder.geocode({'address': 'RU'}, function (results, status) { 
     var ne = results[0].geometry.viewport.getNorthEast(); 
     var sw = results[0].geometry.viewport.getSouthWest(); 

     map.fitBounds(results[0].geometry.viewport);    

     var boundingBoxPoints = [ 
      ne, new google.maps.LatLng(ne.lat(), sw.lng()), 
      sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne 
     ]; 

     var boundingBox = new google.maps.Polyline({ 
      path: boundingBoxPoints, 
      strokeColor: '#FF0000', 
      strokeOpacity: 1.0, 
      strokeWeight: 2 
     }); 

     boundingBox.setMap(map); 
     }); 
    </script> 
</body> 
</html> 

下面是從上面的例子不同國家的截圖。紅色邊界框是地理編碼器返回的視口。注意邊框和實際視之間的差異,如fitBounds()調整:

國家:美國

US

國家:RU

RU

國家:IT

IT

+0

謝謝Daniel。 – jul 2010-03-23 11:41:02

+0

我也很難理解如何做到這一點,真棒詳細的解釋! – designermonkey 2011-04-13 09:18:37

+0

非常感謝您的詳細解釋。 boundingBox是一個很好的主意,可以清楚地說明這一點。 – Symmetric 2012-06-05 05:17:15

2

只是爲了讓你知道用什麼方式這是可以定製的,我準備的,如果你喜歡寬鬆一些boundingBox的在視口中

+1

:(該鏈接的都死了。 – 2013-04-08 13:09:21

+2

固定一個更永久鏈路 – kaskader 2013-04-09 14:49:31

+4

死再次..... – 2013-11-01 22:03:25

相關問題