2015-10-21 37 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 
相關問題