嘿,这绝对是您可以使用 Google Maps API 完成的事情。
您需要确保做的一件重要事情是在尝试让 GMap2 对象重新计算其位置和缩放级别之前更新 GLatLngBounds 对象。
为此,我建议保留 GMarkers 正在使用的所有点的某种数据存储。
使用 GEvent 侦听器,您还可以在移除 GMarker 时将 zoomToBounds 函数绑定到事件。
这是我正在谈论的代码片段:
var bounds = new GLatLngBounds();
var points = {};
function createMarker(location)
{
/*Create Our Marker*/
var point = new GLatLng(location.lat,location.lon);
var marker = new GMarker(point);
/*Add an additional identifier to the Marker*/
marker.myMarkerName = 'uniqueNameToIDMarkerPointLater';
/*Store the point used by this Marker in the points object*/
points[marker.myMarkerName] = point;
/*Create an event that triggers after the marker is removed to call zoomToBounds*/
GEvent.addListener(marker,"remove",function()
{
/*Passes the marker's ID to zoomToBounds*/
zoomToBounds(this.myMarkerName);
};
/*Add the new point to the existing bounds calculation*/
bounds.extend(point);
/*Draws the Marker on the Map*/
map.addOverlay(marker);
}
function zoomToBounds(name)
{
/*Remove the Point from the Point Data Store*/
points[name]=null;
/*Create a new Bounds object*/
bounds = new GLatLngBounds();
/*Iterate through all our points and build our new GLatLngBounds object*/
for (var point in points)
{
if (points[point]!=null)
{
bounds.extend(points[point]);
}
}
/*Calculate the Position and Zoom of the Map*/
map.setCenter(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds)-1);
}
GLatLngBounds 对象不存储用于计算其最大和最小边界的所有点 - 因此需要创建一个新对象来重新定义矩形的边界。
我还创建了一个位于
此处的功能示例。
随意将源代码用于您需要的任何东西 - 让我知道您是如何使用它的,或者如果您有任何其他问题!
这是没有任何注释的代码:
var bounds = new GLatLngBounds();
var points = {};
function createMarker(location)
{
var point = new GLatLng(location.lat,location.lon);
var marker = new GMarker(point);
marker.myMarkerName = 'uniqueNameToIDMarkerPointLater';
points[marker.myMarkerName] = point;
GEvent.addListener(marker,"remove",function()
{
zoomToBounds(this.myMarkerName);
};
bounds.extend(point);
map.addOverlay(marker);
}
function zoomToBounds(name)
{
points[name]=null;
bounds = new GLatLngBounds();
for (var point in points)
{
if (points[point]!=null)
{
bounds.extend(points[point]);
}
}
map.setCenter(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds)-1);
}