簡體   English   中英

Google Maps API v3-fitBounds僅使一個標記居中

[英]Google Maps API v3 - fitBounds centers only one marker

我有一些要檢索的標記,並且想將地圖居中。 是的,我已經閱讀了所有其他答案,但是它似乎對我不起作用: Google Map API v3-設置范圍和中心

JS:

geocoder.geocode( {'address': loc}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var markerBounds = new google.maps.LatLngBounds();
            var coordinate = results[0].geometry.location;
            var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44));   

            //create the marker
            var marker = new google.maps.Marker({
                map: map, 
                position: coordinate,
                visible: true,
                id: type,
                shadow: shadow,
                icon: icon
            });
            markerBounds.extend(coordinate);
            map.fitBounds(markerBounds);
        }
}

您的代碼始終使用只有一個點的LatLngBounds調用fitBounds,即最后一個標記...如果多次調用該函數,則每次調用該函數都會匹配最后一個標記的fitBounds。 您可以在geocoder.geocode函數外部定義markerBounds變量,因此它將保留其值。

var markerBounds = new google.maps.LatLngBounds();
geocoder.geocode( {'address': loc}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coordinate = results[0].geometry.location;
            var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44));   

            //create the marker
            var marker = new google.maps.Marker({
                map: map, 
                position: coordinate,
                visible: true,
                id: type,
                shadow: shadow,
                icon: icon
            });
            markerBounds.extend(coordinate);
            map.fitBounds(markerBounds);
        }
}

現在,markerBounds初始化一次,並使用每個新標記進行擴展。

實際上,您可以通過以下方式記錄邊界中存儲的坐標:

 console.log("mapFitBounds:"+bounds); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

然后只需檢查您的Chrome登錄控制台即可。 您會知道問題所在,因為我發現范圍內有兩個重復的坐標,然后將問題作為目標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM