【问题标题】:Google Maps JavaScript API - Automate Zoom Level?Google Maps JavaScript API - 自动缩放级别?
【发布时间】:2011-03-15 19:19:44
【问题描述】:

我正在使用多个地图标记。目前我在我的 JavaScript 中使用map.fitBounds(bounds); 来调整地图的大小。 bounds 包含多个LatLng 对象。

我做错了什么?因为它缩小得太远了:-(

JavaScript 源代码

var geocoder, map;
$(document).ready(function(){
    var coll_gmap = $(".gmap");
    if ( coll_gmap.length != 0 )
    {
        //initiate map
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 13,
            center: latlng,
           mapTypeControl: true,
            navigationControl: true,
            scaleControl: true,
            navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var bounds = new google.maps.LatLngBounds();
        //loop all addressen + insert into map
          map = new google.maps.Map(coll_gmap[0], myOptions);
        coll_gmap.each(function(index)
        {
             if (geocoder) {
                    geocoder.geocode( { 'address': $(this).attr("address")}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            map.setCenter(results[0].geometry.location);
                            bounds.extend(results[0].geometry.location);

                            var marker = new google.maps.Marker({
                                map: map, 
                                position: results[0].geometry.location
                            });
                        } else {
                            console.log("Geocode was not successful for the following reason: " + status);
                        }//end if status
                    }); //end if geocoder.geocode
                } //end if geocoder   

        }) //end coll_gmap each
        map.fitBounds(bounds);

        }//end if coll_gmap length
       /* console.log("Script created by NicoJuicy");*/   
}); //end onload

HTML 源代码

<div class="gmap" address="SomeAddress1" style="width:700px;height:350px"></div>
<div class="gmap" address="someAddress2"></div>

【问题讨论】:

    标签: javascript google-maps-api-3 zooming bounds


    【解决方案1】:

    fitBounds() 方法应该可以工作。但是请注意,它总是在地图大小上保留一些填充。考虑以下示例:

    <!DOCTYPE html>
    <html> 
    <head> 
       <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
       <title>Google Maps fitBounds Padding</title> 
       <script src="http://maps.google.com/maps/api/js?sensor=false" 
               type="text/javascript"></script> 
    </head> 
    <body> 
       <div id="map" style="width: 543px; height: 350px;"></div> 
    
       <script type="text/javascript"> 
          var map = new google.maps.Map(document.getElementById('map'), { 
            mapTypeId: google.maps.MapTypeId.ROADMAP 
          });
    
          var bounds = new google.maps.LatLngBounds();
    
          var points = [
            new google.maps.LatLng(51.22, 4.40),
            new google.maps.LatLng(50.94, 3.13)
          ];
    
          // Extend bounds with each point
          for (var i = 0; i < points.length; i++) {
            bounds.extend(points[i]);
            new google.maps.Marker({position: points[i], map: map});
          }
    
          // Apply fitBounds
          map.fitBounds(bounds);  
    
          // Draw the bounds rectangle on the map
          var ne = bounds.getNorthEast();
          var sw = bounds.getSouthWest();
    
          var boundingBox = new google.maps.Polyline({
            path: [
              ne, new google.maps.LatLng(ne.lat(), sw.lng()),
              sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
            ],
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2
          });
    
          boundingBox.setMap(map);
       </script> 
    </body> 
    </html>
    

    上例截图:

    红色边界框代表LatLngBounds 对象在使用两个标记进行扩展时。注意地图画布的宽度是543px,还要注意边界框左右的内边距。

    现在,如果我们将地图画布的宽度仅减少1px,使用542pxfitBounds() 方法将弹出到较低的缩放级别:

    【讨论】:

    • 反应不错。不过,我不得不怀疑,如果你注意到我的截图,我的标记不在中间,更多的是在左半边。所以其他的东西一定是错的,而且,当我调整宽度时,缩放不会变得“更近”......
    • @NicoJuicy:是否可以通过复制您的问题的完整示例来更新您的问题?我尝试将标记放置在与您相同的位置,fitBounds() 在我的屏幕截图中似乎工作得更好。
    【解决方案2】:

    我使用右侧的“相关”链接来到这里,我认为您的问题的答案与上一个问题的答案相同。 :p

    看,问题是每次您使用平移/缩放地图的功能时,脚本都会忽略新的、类似的输入,直到它再次准备好。因此,您必须检测到这一点,并且只有在它被接受时才调用 fitBounds() 。尝试更换您的

    map.fitBounds(bounds);
    

    var listener = google.maps.event.addListener(map, "idle", function() { 
                   map.fitBounds(bounds);
                   google.maps.event.removeListener(listener); });
    

    祝你好运。

    【讨论】:

      【解决方案3】:

      只需使用 setZoom 功能。

      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({ 'address': zipcode }, function(results, status)
      {
          if (status == google.maps.GeocoderStatus.OK)
          {
              map.setCenter(results[0].geometry.location);
              map.setZoom(12);
          }
          else
          {
              alert(zipcode + " not found" + "\nstatus : " + status);
          }
      });
      

      【讨论】:

        【解决方案4】:

        我找到了解决办法。

        而不是做一个单独的

        bounds.extend(myLatLng)
        

        每次将 myLatLng 添加到边界时,请执行以下操作

        bounds = map.getBounds();
        bounds.extend(results[0].geometry.location);
        map.fitBounds(bounds);
        

        希望这对任何人都有帮助!

        【讨论】:

          【解决方案5】:
          //Custom zoom if you have just type of geocode response    
          function get_node(node_name){
          return document.getElementById(node_name);
          }
          
          var map_options = {};
          var options = {
              'zoom'      : LB_listing.zoomopt,
              'minZoom'   : 3,
              'center'    : latlng,
              'mapTypeId' : google.maps.MapTypeId.ROADMAP
          };
          map_options.map = new google.maps.Map(get_node('googleMap'), options);
          
          
          geocoder = new google.maps.Geocoder();
          var address = $("#search_location").val();
          geocoder.geocode( { 'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                  switch(results[0].types[0]){
                      case 'street_address':
                          map_options.zoomopt = 6;
                          break;
                      case 'route':
                          map_options.zoomopt = 14;
                          break;
                      case 'bus_station':
                          map_options.zoomopt = 14;
                          break;
                      case 'intersection':
                          map_options.zoomopt = 6;
                          break;
                      case 'political':
                          map_options.zoomopt = 14;
                          break;
                      case 'country':
                          map_options.zoomopt = 5;
                          break;
                      case 'administrative_area_level_1':
                          map_options.zoomopt = 6;
                          break;
                      case 'administrative_area_level_2':
                          map_options.zoomopt = 6;
                          break;
                      case 'administrative_area_level_3':
                          map_options.zoomopt = 6;
                          break;
                      case 'administrative_area_level_4':
                          map_options.zoomopt = 6;
                          break;
                      case 'administrative_area_level_5':
                          map_options.zoomopt = 6;
                          break;
                      case 'colloquial_area':
                          map_options.zoomopt = 6;
                          break;
                      case 'locality':
                          map_options.zoomopt = 11;
                          break;
                      case 'ward':
                          map_options.zoomopt = 6;
                          break;
                      case 'sublocality':
                          map_options.zoomopt = 6;
                          break;
                      case 'neighborhood':
                          map_options.zoomopt = 14;
                          break;
                      case 'premise':
                          map_options.zoomopt = 6;
                          break;
                      case 'subpremise':
                          map_options.zoomopt = 6;
                          break;
                      case 'postal_code':
                          map_options.zoomopt = 6;
                          break;
                      case 'natural_feature':
                          map_options.zoomopt = 6;
                          break;
                      case 'airport':
                          map_options.zoomopt = 6;
                          break;
                      case 'park':
                          map_options.zoomopt = 6;
                          break;
                      case 'point_of_interest':
                          map_options.zoomopt = 6;
                          break;
                      default:
                          map_options.zoomopt = 6;
                          break;
                  }
                  map_options.newLocation(results[0].geometry.location.lat(),results[0].geometry.location.lng());
              }else {
                  $('#message_error').show().delay(3000).fadeOut(1000);
                  $('#message_error_msg').html("Geocode was not successful for the following reason: " + status);
              }
          });
          
          map_options.newLocation = function(newLat,newLng) {
          map_options.map.setCenter({
              lat : newLat,
              lng : newLng
          });
          map_options.map.setZoom(map_options.zoomopt);
          

          }

          【讨论】:

          • 欢迎来到 SO。您的意见总是受欢迎的,但通常一些注释也很好
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-04
          • 1970-01-01
          • 1970-01-01
          • 2013-07-21
          • 2013-12-27
          • 2015-03-23
          • 2014-01-15
          相关资源
          最近更新 更多