【问题标题】:How to set the Google Map zoom level to show all the markers?如何设置谷歌地图缩放级别以显示所有标记?
【发布时间】:2011-01-22 16:05:27
【问题描述】:

如何设置缩放级别以在 Google 地图上显示所有标记?

在我的 Google 地图中,不同位置有不同的标记。我想根据标记范围设置谷歌地图缩放级别(这意味着在谷歌地图的视图中,我想查看所有标记)

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    你去吧:

    <!DOCTYPE html>
    <html> 
    <head> 
       <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
       <title>Google Maps getBoundsZoomLevel Demo</title> 
       <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false" 
               type="text/javascript"></script> 
    </head> 
    <body onunload="GUnload()"> 
    
       <div id="map" style="width: 400px; height: 300px"></div> 
    
       <script type="text/javascript"> 
    
       if (GBrowserIsCompatible()) {
          var map = new GMap2(document.getElementById("map"));
          var markerBounds = new GLatLngBounds();
    
          for (var i = 0; i < 10; i++) {
             var randomPoint = new GLatLng( 39.00 + (Math.random() - 0.5) * 20, 
                                           -77.00 + (Math.random() - 0.5) * 20);
    
             map.addOverlay(new GMarker(randomPoint));
             markerBounds.extend(randomPoint);
          }
    
          map.setCenter(markerBounds.getCenter(), 
                        map.getBoundsZoomLevel(markerBounds));
       }
       </script> 
    </body> 
    </html>
    

    我们在上面的例子中创建了 10 个随机点,然后将每个点传递给 GLatLngBounds.extend()。最后我们用GMap2.getBoundsZoomLevel() 得到正确的缩放级别。

    【讨论】:

      【解决方案2】:

      设置 Google 地图缩放级别以显示所有标记?

      地图 API v3

      1. 获取标记
      2. 获取标记的边界
      3. 通过将地图拟合到标记边界来设置地图中心

      var markers = [markerObj1, markerObj2, markerObj3];
      
      var newBoundary = new google.maps.LatLngBounds();
      
      for(index in markers){
        var position = markers[index].position;
        newBoundary.extend(position);
      }
      
      map.fitBounds(newBoundary);
      

      上面的代码将自动居中并缩放您的地图,以便所有标记都可见。

      【讨论】:

        【解决方案3】:

        如果您使用的是 API 版本 3,您可以替换

        map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds));
        

        map.fitBounds(markerBounds).
        

        【讨论】:

          【解决方案4】:

          您可以使用GLatLngBounds 对象的extend 方法,它表示地图上的一个矩形。

          var bounds = new GLatLngBounds();
          

          围绕地图上的所有 points 循环,为每个扩展 GLatLngBounds 对象的边界。

          bounds.extend(myPoint);
          

          最后,您可以使用 bounds 对象来设置地图的中心和缩放(map 是您的地图对象)

          map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-25
            • 2012-07-12
            • 2017-04-10
            相关资源
            最近更新 更多