如何在Google Maps Javascript API中计算多边形的中心点?

4
假设我有一个多边形数组,其中包含一堆用于在地图上绘制这些区域的纬度/经度坐标:
// These polygons are just an example to illustrate structure, they are not my actual polygons

var polygons = [ 
    [
       {lat: 1, lng: 2},
       {lat: 3, lng: 4},
       {lat: 5, lng: 6},
       {lat: 1, lng: 2},
    ],
    [
       {lat: 7, lng: 8},
       {lat: 9, lng: 10},
       {lat: 11, lng: 12},
       {lat: 7, lng: 8},
    ],
];

当初始化地图时,如何将地图的初始视口设置为围绕所有多边形居中?
这是一张说明我意思的图片:

How I want the map to behave

2个回答

4
你可以构造一个LatLngBounds对象。对于多边形中的每个点,将该Bounds对象扩展以包括该点。然后更新地图以适应这些边界。
类似这样:
var bounds = new google.maps.LatLngBounds();

for (var i = 0; i < polygons.length; i++) {
    for (var j = 0; j < polygons[i].length; j++) {
        bounds.extend(polygons[i][j]);
    }
}

map.fitBounds(bounds);
map.setCenter(bounds.getCenter());

你可能会遇到一个问题,我不确定 bounds.extend 是否能够与 {lat: 1, lng: 2} 这种格式的点一起使用。你可能需要构建 LatLng 对象。
如果是这种情况,代码应该是这样的:
bounds.extend(new google.maps.LatLng(polygons[i][j].lat, polygons[i][j].lng));

LatLngBounds有一个方法.extend(LatLng)。只需迭代所有多边形中的所有点并将它们提供给新的LatLngBounds实例的extend方法即可。最终你会得到一个对象,可以与map.fitBounds(LatLngBounds)一起使用。 - Dykam

-1

这只是我旧项目中的一小段代码

var styledMap = new google.maps.StyledMapType(styles);

var mapOptions = {
    //backgroundColor: '#000',
    //draggable:false,
    scrollwheel: false,
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    disableDoubleClickZoom: true,
    overviewMapControl: false,
    panControl: false,
    rotateControl: false,
    streetViewControl: false,
    zoomControl:false,
    noClear: true,
    zoom: 6,
    center: new google.maps.LatLng(12.1, 122), //<----- set the center here
    mapTypeId: google.maps.MapTypeId.SATELLITE
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

map.mapTypes.set('map_style', styledMap);`enter code here`

请查看上面代码中的center属性。
center: new google.maps.LatLng(12.1, 122), //<----- set the center here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接