Google地图中的fitbounds()api V3不适合边界

jul*_*jul 32 javascript google-maps google-maps-api-3 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))
    }
);
Run Code Online (Sandbox Code Playgroud)

Dan*_*llo 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>
Run Code Online (Sandbox Code Playgroud)

以下是上述示例中各个国家/地区的屏幕截图.红色边界框是地理编码器返回的视口.注意边界框和实际视口之间的差异,调整方式如下fitBounds():

国家:美国

我们

国家:RU

RU

国家:IT

它