fitbounds() in Google maps api V3 does not fit bounds

回眸只為那壹抹淺笑 提交于 2019-11-27 11:28:30
Daniel Vassallo

This happens because the fitBounds() needs to snap to a viewport that fits the map canvas using the maximum zoom level possible. On the other hand, the viewport returned by the geocoder is not dependent on the size, layout or zoom level of the map canvas. Therefore the fitBounds() method adjusts the map's viewport in order to view the passed LatLngBounds in full at the centre of the map.

You may want to check the following example for a clearer demonstation:

<!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>

Below are some screenshots for various countries from the above example. The red bounding box is the viewport returned by the geocoder. Note the difference between the bounding box and the actual viewport, as adjusted by fitBounds():

Country: US

Country: RU

Country: IT

Just to let you know in what way this can be customized, I have prepared a sample of what you can do if you prefer to loose some of the boundingBox in the viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!