我试图扩展几个多边形的地图边界,但似乎它只是扩展了循环中最后一个多边形的边界。我有什么错误的建议?
function FitBounds(){
for (var i=0; i < shapes2.length; i++){
var paths = shapes2[i].getPaths();
var bounds= new google.maps.LatLngBounds();
paths.forEach(function(path){
var ar = path.getArray();
for(var i=0, l = ar.length; i <l; i++){
bounds.extend(ar[i]);
}
})
}
map.fitBounds(bounds)
}
答案 0 :(得分:8)
在循环外创建边界。
function FitBounds(){
var bounds= new google.maps.LatLngBounds();
for (var i=0; i < shapes2.length; i++){
var paths = shapes2[i].getPaths();
paths.forEach(function(path){
var ar = path.getArray();
for(var i=0, l = ar.length; i <l; i++){
bounds.extend(ar[i]);
}
})
}
map.fitBounds(bounds)
}
答案 1 :(得分:0)
供其他人参考,谷歌地图库提供了帮助方法,可以更轻松地获取形状集合的边界:
function FitBounds(){
var bounds = shapes2.reduce((boundsAccumulator, shape) =>
boundsAccumulator.union(shape.getBounds()), new google.maps.LatLngBounds())
map.fitBounds(bounds)
}
或者如果你不喜欢 reduce
function FitBounds(){
var bounds = new google.maps.LatLngBounds()
shapes2.forEach(shape) => bounds.union(shape.getBounds()))
map.fitBounds(bounds)
}