如何为地图上的所有形状调整边界

How can I fitBounds for all shapes on the map?

本文关键字:调整 边界 地图      更新时间:2023-09-26

地图上有很多形状,它们都保存在这个数组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);

但它们都只适用于一种形状,而不是一种以上的形状。似乎只有三种形状。(圆形、矩形、多边形)。

我想在单击运行函数的按钮时适合地图上的所有形状。

您需要创建一个 google.maps.LatLngBounds 对象,该对象是要显示的所有对象的边界的并集。

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

伪代码(您需要将要在地图上显示的所有形状的边界添加到其中):

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); 
<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>