适合多个多边形 google 地图的边界
Fit Bounds for Multiple Polygons google Maps
我正在尝试扩展多个多边形的地图边界,但它似乎只扩展了循环中最后一个多边形的边界。关于我哪里出错的任何建议?
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)
}
在循环外创建边界。
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)
}
仅供其他人参考,google 地图库提供了辅助方法,可以更轻松地获取形状集合的边界:
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)
}
我正在尝试扩展多个多边形的地图边界,但它似乎只扩展了循环中最后一个多边形的边界。关于我哪里出错的任何建议?
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)
}
在循环外创建边界。
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)
}
仅供其他人参考,google 地图库提供了辅助方法,可以更轻松地获取形状集合的边界:
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)
}