Reputation: 13
How can i get the bounds of several kml file ? i can get easely for one kml file but i am a little be lost ... to get the bounds of all kml file who are in the map ...
here is the code (write in php file context)
at first i define the kml file needed and the js var for sources and layers (ie : src_expe_pro0 expe_pro0 ...)
$pro_kml .= '
var src_expe_pro'.$j.' =new ol.source.Vector({
url: "http://www.grottes-et-karsts-de-chine.org/gkc_kml_file/pro_kml_file/'.strtolower($pro_id).'.kml",
format: new ol.format.KML()
});
var expe_pro'.$j.' = new ol.layer.Vector({
source:src_expe_pro'.$j.'
});';
$layers_pro_kml .= "expe_pro".$j.",
";
later i put this in the map (so $layers_pro_kml can be one or several layer(s))
...
layers: [
fond_carte,
'.$layers_pro_kml.'
expe_markers
],
...
and here come the fog ... for now i simply use this who work taking the bound of the first kml layer
expe_pro0.once("change", function(e){
var extension = src_expe_pro0.getExtent();
map.getView().fit(extension);
});
so in fact the question is how to work with the arrays (extension) to reduce at one array we will give me the bounds of all the kml layers ? is there a fonction in the api or must i play with the arrays ?? or perhaps a simple way ?
Any advice
Thanks
With the advice of mike (thanks) i use this and its work perfectly ..
var extension = ol.extent.createEmpty();
map.getLayers().forEach(function(layer){
if(!layer.values_.id) {
layer.once("change", function(e){
ol.extent.extend(extension, layer.getSource().getExtent());
map.getView().fit(extension);
});
}
});
Upvotes: 1
Views: 886
Reputation: 17972
Try something like this. The sources might load in any order so it would be simplest to re-fit as each loads.
// before opening map set listeners for vectors loading
// and use extents to fit the map
var extension = ol.extent.createEmpty();
[
fond_carte,
'.$layers_pro_kml.'
expe_markers
].forEach(function(layer) {
if (layer.getSource().getExtent) {
layer.getSource().on("addfeature", function(e){
ol.extent.extend(extension, layer.getSource().getExtent());
map.getView().fit(extension);
});
}
});
// then open the map to load the vectors
map.setView(
new ol.View({
center: [0,0],
zoom: 0
})
);
Upvotes: 1