2016-06-11 147 views
-1

我有一張地圖顯示用戶的「簽到」。我需要在2種情況,以應付這個地圖的第一時間顯示:如何在地區或標記周圍放置地圖?

  1. 該用戶從未簽到:在這種情況下,我想縮小到這樣的水平,這顯示特定「區域」。該地區被稱爲「南非西開普省」。所以基本上這個map,但放大,所以紅色區域在地圖的邊緣,你只能看到。
  2. 如果用戶已經簽入到一個或多個地方,我想放大,使用戶只看到他在已經檢查到的地方的特寫圖例如:

enter image description here

所以紅色的「塊」是我想在地圖上看到的區域。不是整個小睡。

這是我如何創建地圖:

mapDiv = document.getElementById('map'); 
map = new google.maps.Map(mapDiv, { 
    center: markerLocation, 
    zoom: zoomLevel, 
}); 

然後,我加上「標記」爲簽入:

marker = new google.maps.Marker({ 
    position: markerLocation, 
    label: '', 
    icon: 'img/map_marker.png', 
    map: map 
}); 

所以我的猜測是,我需要把重點放在「放大水平」。因爲這決定了顯示地圖的多少。但請記住,這張地圖非常靈敏,所以高度和寬度都會有所不同。此外,標記可以放置在各種不同的地方。

那麼如何計算ZoomLevel來僅顯示相關信息呢?即只有包含地圖標記的區域,或者如果沒有地圖標記,則只包含西開普省的區域?

UPDATE

我認爲對於第一個問題,我能找到西開普省的中心,並用其作爲地圖的「中心」。這很簡單。如果只有一次入住,這也很容易。但是如果有超過1次登機手續,你如何找到地圖的中心?事實上,即使是2分也許不會太難,但你如何找到許多分的中心?!

回答

3

google.maps.LatLngBounds是一個對象,其被設計成容納矩形邊界。它可以通過兩種方式創建:

  1. 通過傳遞它的邊界作爲參數到constructior:var my_bounds = new google.maps.LatLngBounds({east: -34, north: 151, south: -34, west: 151});
  2. 或者創建空var my_bounds = new google.maps.LatLngBounds();這將創建一個沒有座標的邊界,並且您將使用方法添加到它們中的任何座標,將對它們進行放大。所以如果你extend它與座標lat:20, lng:-12你會得到界限{e:20, n:-12, s:-12, w:20}那麼如果你將extend它進一步與lat:22, lng:10你會得到界限{e:22, n:10, s:-12, w:20}等等。

google.maps.Map的功能在某種程度上fitBounds(bounds)的作品,它計算最接近的縮放級別包含您所創建的邊界(視可能大於bounds過去了,但從未較小)和中心,這是的中心bounds矩形,然後使用計算的值縮放和居中地圖。

所以解決您的問題:

1.To變焦「西開普省,南非」,創建這個區域,這是CCA south:-34.985081, west:17.811984, north:-30.016613, east:24.265440氣盛視到它的硬編碼值的範圍,所以你會有:

var western_cape_bounds = new google.maps.LatLngBounds({east: 24.265440, north: -30.016613, south: -34.985081, west: 17.811984}); 
map.fitBounds(western_cape_bounds); 

2.如果您有很多標記,那麼你需要extend邊界,然後配合視遍歷所有這些,放進去:

var marker_bounds = new google.maps.LatLngBounds(); 
for(var i = 0; i < markers.length; i++){ 
    marker_bounds.extend(markers[i].getPosition()); 
    //alternatively, if you don't have markers created yet, you can extend the bounds like this: marker_bounds.extend({lat: MY_LAT, lng:MY_LNG}); 
} 
map.fitBounds(marker_bounds); 
1

可以使用fitBounds方法來設置視口以包含指定界限(documentation

var myBounds = new google.maps.LatLngBounds(); 
myBounds.extend(myMarker1); 
myBounds.extend(myMarker2); 

map.fitBounds(myBounds); 
相關問題