提问人:Simon 提问时间:2/1/2010 最后编辑:John CondeSimon 更新时间:12/25/2022 访问量:28182
如何让 Google 地图显示整个多边形?
How do I get Google Maps to show a whole polygon?
问:
我有一组 GPolygon 对象,这些对象附加到我的域模型中的对象,并添加到我页面上的地图中。域对象显示在同一页面上的列表中,当用户单击其中一个对象时,我想显示关联的多边形。
我希望显示整个多边形,理想情况下,我希望地图以多边形中心为中心。
我希望会有一个地图API调用,就像...
myMap.makeSureYouCanSeeAllThisPolygon(aPolygon);
但我一直找不到。
如果我必须手动执行此操作,那么我显然可以轻松确定居中,但是如何确定缩放?
答:
您可以通过使用,然后使用返回的方法获取多边形的中心点。aPolygon.getBounds().getCenter();
GLatLng
myMap.setCenter()
要获得缩放级别,您可以使用然后将其与方法一起使用。myMap.getBoundsZoomLevel(aPolygon.getBounds());
myMap.setZoom()
评论
Google Maps v3 API 本身不支持 google.maps.Polygon 类的方法。这似乎很奇怪,因为google.maps.Map类有一个方法,这正是你要找的。如果您以任何频率使用 Google Maps API,那么这应该在您的技巧包中 ::getBounds()
fitBounds()
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;
}
有了这种方法,就可以非常简单地在地图上居中和拟合多边形。
注意:如果您不熟悉,那也没关系,它们是 google.maps.MVCArray 类独有的方法。当您调用多边形的方法时,它会将 LatLng 的数组作为 LatLng 的可变 MVCArray 返回。你可以在这里准备好MVCArrays - Google Maps v3 API MVCArray类。getAt()
getLength()
getPaths()
继续前进。这是框架,您必须在下一段代码之前的某个地方实现上面的原型方法。
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());
评论
path = paths.getAt(p);
path = paths.getAt(i);
此解决方案适用于我已经成功添加到地图中的多边形。为 google.maps.Polygon 类添加 getBounds() 方法,然后使用 map.fitBounds(myPolygon.getBounds());
认为他想到:
map.fitBounds(myPolygon.my_getBounds());
工作是一种享受。
我写了一个函数来添加到Kevin James解决方案中。它采用一个多边形数组,并获取地图上可能拥有的所有多边形的边界。你只需要把它们推到一个数组上,然后你就可以调用我的函数来自动缩放地图。
function getArrayBounds(polyArray){
var bounds = new google.maps.LatLngBounds();
var path, paths;
for(var polys = 0; polys < polyArray.length; polys++) {
paths = polyArray[polys].getPaths();
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;
}
评论
for
polygonsArray.forEach(polygon => polygon.getPaths().forEach(path => path.forEach(latLng => bounds.extend(latLng))));
let bounds = new google.maps.....
return bounds;
用 ES6 编写的 getBounds 函数的较短版本
google.maps.Polygon.prototype.getBounds = function () {
let bounds = new google.maps.LatLngBounds();
this.getPaths().forEach(p => {
p.forEach(element => bounds.extend(element));
});
return bounds;
}
将地图居中
map.fitBounds(poly.getBounds());
评论