【问题标题】:How can I fitBounds for all shapes on the map?如何为地图上的所有形状拟合边界?
【发布时间】:2013-11-22 03:00:20
【问题描述】:

地图上有很多形状,它们都保存在这个数组array_shapes_object[]中。如何通过 fitBounds 方法将它们全部显示在地图上?

我可以使用类似的东西:

map.fitBounds(circle.getBounds());

map.fitBounds(rectangle.getBounds());

var points = new google.maps.LatLng(arrayLatitude[aa], arrayLongitude[aa]);
bounds.extend(points);
map.fitBounds(bounds);

但它们都只适用于一个形状,不超过一个。 似乎只有三种形状。 (圆形、矩形、多边形)。

当我点击一个运行函数的按钮时,我想在地图上设置所有形状的边界。

【问题讨论】:

    标签: javascript google-maps-api-3 fitbounds


    【解决方案1】:

    您需要创建一个google.maps.LatLngBounds 对象,它是您要显示的所有对象的边界的联合。

    联合(其他:LatLngBounds)| LatLngBounds |扩展 this 边界以包含 this 和给定边界的并集。

    伪代码(你需要把你想在地图上显示的所有形状的边界都加进去):

    var bounds = circle.getBounds();
    bounds.union(rectangle.getBounds();
    for (var aa=0; aa < arrayLatitude.length; aa++) {
      var points = new google.maps.LatLng(arrayLatitude[aa], arrayLongitude[aa]);
      bounds.extend(points);
    }
    map.fitBounds(bounds); 
    

    【讨论】:

    • 有趣的是,我不得不使用 bounds.union(circle.getBounds()); 将我所有的圈子都显示在地图上
    【解决方案2】:
    <script>
    //This function get the canter of map in a way that all shapes are shown on the map.
    function get_center()
    {
        var bounds = new google.maps.LatLngBounds();
        var points = new Array();
    
        for(var counter = 0; counter < array_shapes_object.length; counter++)
        {
            switch(array_shapes_object[counter].type)
            {           
                case "rectangle":
                case "circle":                                            
                  points = new google.maps.LatLng(array_shapes_object[counter].getBounds().getNorthEast().lat(), array_shapes_object[counter].getBounds().getNorthEast().lng());
                  bounds.extend(points);
    
                  points = new google.maps.LatLng(array_shapes_object[counter].getBounds().getSouthWest().lat(), array_shapes_object[counter].getBounds().getSouthWest().lng());
                  bounds.extend(points);
                break;
    
                case "polygon":
                  var paths;
                  paths = array_shapes_object[counter].getPath();
    
                  for(var i = 0; i < paths.length; i++)
                  {
                      points = new google.maps.LatLng(paths.getAt(i).lat(), paths.getAt(i).lng());
                      bounds.extend(points);                  
                  }
    
                break;
            }
    
            map.fitBounds(bounds);
        }               
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多