Google Maps v3 API 本身不支持 google.maps.Polygon 类的 getBounds() 方法。这似乎很奇怪,因为 google.maps.Map 类有一个 fitBounds() 方法,这正是您正在寻找的。如果您以任何频率使用 Google Maps API,那么这应该在您的套路::
getBounds() google.maps.Polygon 类的方法
google.maps.Polygon.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var i = 0; i < paths.getLength(); i++) {
path = paths.getAt(i);
for (var ii = 0; ii < path.getLength(); ii++) {
bounds.extend(path.getAt(ii));
}
}
return bounds;
}
有了这个方法,在地图上居中和拟合多边形变得非常简单。
注意:如果您不熟悉 getAt() 和 getLength() 没关系,它们是 google.maps.MVCArray 类独有的方法。当您调用多边形的 getPaths() 方法时,它会将您的 LatLng 数组作为 LatLng 的可变 MVCArray 返回。您可以在此处准备 MVCArrays - Google Maps v3 API MVCArray class。
继续前进。这是框架,您必须在下一段代码之前的某个地方实现上面的原型方法。
var map = new google.maps.Map(container, opts); // I'll spare the details on this
var coords = [
new google.maps.LatLng(25.774252, -80.190262)
,new google.maps.LatLng(18.466465, -66.118292)
,new google.maps.LatLng(32.321384, -64.75737)
,new google.maps.LatLng(25.774252, -80.190262)
];
var myPolygon = new google.maps.Polygon({
paths: coords
,strokeColor: "#A80000"
,strokeOpacity: 0.8
,strokeWeight: 1
,fillColor: "#0b2a32"
,fillOpacity: 0.12
});
使用舞台布景,您只需:::
map.fitBounds(myPolygon.getBounds());
短而甜。希望对您有所帮助。
-凯文·詹姆斯