2015-10-21 36 views
3

比方说,我有个多边形组成的数组,其中包含了一些用来在地图上绘制这些地区经/纬度坐标:如何计算Google Maps JavaScript API中多个多边形的中心?

// 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

回答

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

你能用一些代码演示? – Weblurk

+0

'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: new google.maps.LatLng(12.1, 122), //<----- set the center here 
相关问题