問題はこれです:私たちは設定しました
var bounds = new google.maps.LatLngBounds();
後でマップ上の境界領域にマーカーを合わせることができるようにします。GMaps は常に fitBounds() に応じて非同期的にズームアウトしますが、同じことを達成するためにズームインすることはありません (以前に @broady によって指摘されたように)。これは、多くのアプリケーションにとって理想的ではありません。一度マップをズームアウトする原因となった一連のマーカーをマップ上に表示すると (おそらく 10 未満)、ユーザーが手動でズームインしないと元に戻りません。
GMaps は、(より適切な言葉がない) 最もズームアウトされたマーカー コレクション ステータスの境界を引き続き使用します (申し訳ありません)。新しいマーカーの各呼び出しの前に「null」に設定すると、操作する新しいマップが得られます。
自動ズームインするには、LatLngBounds(); を設定するだけです。そのように「null」にします(その配置を確認するには、以下の疑似例を参照してください):
bounds = new google.maps.LatLngBounds(null);
疑似例:
// map stuff/initiation
...
var bounds = new google.maps.LatLngBounds();
var gmarkers = [];
function CreateMarker (obj) {
myLatLng = new google.maps.LatLng(obj['latitude'], obj['longitude']);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(obj['job']);
infowindow.open(map, marker);
}
})(marker, i));
bounds.extend(myLatLng);
gmarkers.push(marker);
}
....
// here's an AJAX method I use to grab marker coords from a database:
$.ajax({
beforeSend: function() {
clear_markers(gmarkers); // see below for clear_markers() function declaration
},
cache: false,
data: params,
dataType: 'json',
timeout: 0,
type: 'POST',
url: '/map/get_markers.php?_=<?php echo md5(session_id() . time() . mt_rand(1,9999)); ?>',
success: function(data) {
if (data) {
if (data['count'] > 0) {
var obj;
var results = data['results'];
// Plot the markers
for (r in results) {
if (r < (data['count'])) {
CreateMarker(results[r]);
}
}
}
}
},
complete: function() {
map.fitBounds(bounds);
}
});
// clear_markers()
function clear_markers(a) {
if (a) {
for (i in a) {
a[i].setMap(null);
}
a.length = 0;
}
bounds = new google.maps.LatLngBounds(null); // this is where the magic happens; setting LatLngBounds to null resets the current bounds and allows the new call for zoom in/out to be made directly against the latest markers to be plotted on the map
}