我在地圖上設置了多個標記,我可以靜態設置縮放級別和中心,但我想要的是覆蓋所有標記並儘可能縮放,使所有市場都可見中心/設置地圖縮放以覆蓋所有可見的標記?
可用方法如下
和
既不setCenter
支持多重峯IPLE場所或數組輸入也setZoom
確實有這種類型的功能
我在地圖上設置了多個標記,我可以靜態設置縮放級別和中心,但我想要的是覆蓋所有標記並儘可能縮放,使所有市場都可見中心/設置地圖縮放以覆蓋所有可見的標記?
可用方法如下
和
既不setCenter
支持多重峯IPLE場所或數組輸入也setZoom
確實有這種類型的功能
您需要使用fitBounds()
方法。
var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
要使用一些有用的技巧延長給出答案:
var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
//center the map to a specific spot (city)
map.setCenter(center);
//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
map.setZoom(15);
}
//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
map.setMaxZoom(15);
map.fitBounds(bounds);
map.setMaxZoom(Null)
}
UPDATE:
在主題表明fitBounds()是一個asynchronic 進一步研究並且最好在調用擬合邊界之前使用定義的偵聽器進行縮放操作。
感謝@Tim,@ xr280xr,議題是更多的例子:SO:setzoom-after-fitbounds
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
好的補充。謝謝! –
我有undefined由.getZoom()返回。 [這個答案](http://stackoverflow.com/a/13435411/263832)幫助我通過使用'zoom_changed'上的'addListenerOnce'來設置縮放後的縮放值。 – xr280xr
謝謝@ d.raev,但設置邊界已設置時的最大縮放比例不起作用。你必須做的是在初始化你的地圖時設置「maxZoom」選項。 https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapOptions – Tim
沒有可用於谷歌地圖這個MarkerClusterer
客戶端工具,那麼具體的Google Map developer Articles,這裏是什麼是很簡短的使用說明:
有許多方法做你問什麼:
您可以在上面提供的鏈接,閱讀它們。
Marker Clusterer
使用基於網格的聚類聚集希望網格的所有標記。基於網格的聚類通過將地圖劃分爲一定大小的正方形(每個縮放大小發生變化),然後將這些標記分組到每個網格正方形中來工作。
後,我希望這是你要找的人&什麼,這將解決您的問題:)
數組的大小必須大於零。 其他方面你會有意想不到的結果。
function zoomeExtends(){
var bounds = new google.maps.LatLngBounds();
if (markers.length>0) {
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
myMap.fitBounds(bounds);
}
}
見http://stackoverflow.com/questions/2362337/how-to-set-the-google-map-zoom-level-to-show-all-the-markers – palmsey
你需要添加每次添加標記時將'latlng'設置爲'bounds'對象,並將地圖設置爲適合最終邊界。請參閱此處的答案:http://stackoverflow.com/questions/1556921/google-map-api-v3-set-bounds-and-center?rq=1 –