代码之家  ›  专栏  ›  技术社区  ›  airportyh

如何在googlemapsjsapi中获得仍然包含一组Lat/Long坐标的最小LatLngBounds?

  •  5
  • airportyh  · 技术社区  · 15 年前

    我需要在地图上绘制一组坐标以响应用户的选择,当发生这种情况时,我希望平移地图以聚焦于这组点。如何找到包含所有坐标的最小边界框(LatLngBounds)?

    1 回复  |  直到 15 年前
        1
  •  12
  •   Community Mohan Dere    8 年前

    除了 Stack Overflow post which @Crescent Fresh pointed to above (使用的是v2api),您希望使用的方法是 LatLngBounds.extend()

    下面是一个完整的示例,使用 v3 API :

    <!DOCTYPE html>
    <html> 
    <head> 
       <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
       <title>Google Maps LatLngBounds.extend() Demo</title> 
       <script src="http://maps.google.com/maps/api/js?sensor=false" 
               type="text/javascript"></script> 
    </head> 
    <body> 
       <div id="map" style="width: 400px; height: 300px;"></div> 
    
       <script type="text/javascript"> 
    
       var map = new google.maps.Map(document.getElementById('map'), { 
         mapTypeId: google.maps.MapTypeId.TERRAIN
       });
    
       var markerBounds = new google.maps.LatLngBounds();
    
       var randomPoint, i;
    
       for (i = 0; i < 10; i++) {
         // Generate 10 random points within North East America
         randomPoint = new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20, 
                                              -77.00 + (Math.random() - 0.5) * 20);
    
         // Draw a marker for each random point
         new google.maps.Marker({
           position: randomPoint, 
           map: map
         });
    
         // Extend markerBounds with each random point.
         markerBounds.extend(randomPoint);
       }
    
       // At the end markerBounds will be the smallest bounding box to contain
       // our 10 random points
    
       // Finally we can call the Map.fitBounds() method to set the map to fit
       // our markerBounds
       map.fitBounds(markerBounds);
    
       </script> 
    </body> 
    </html>
    

    截图:

    Google Maps LatLngBounds.extend() Demo

    推荐文章