I have a layer in OpenLayers (version 5) that is only shown when the user types four values: codigo_setor, codigo_quadra, codigo_lote and if you want to show only the searched lot or the whole block, referring to the searched lot.
After typing the values, click on a button, which will create the layer with the filters:
var my_layer;
function setLayerLoteFiscal(codigo_setor, codigo_quadra, codigo_lote, show){
if (show){
my_layer = new ol.layer.Vector({
name: 'my_layer',
visible: true,
style: my_style,
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: function(extent) {
return urlGeoserver +'wfs?service=WFS&' +
'version='+versionGeoserver+'&request=GetFeature&typename=geo:MY_LAYER&' +
'&outputFormat=application/json&srsname=EPSG:4326&' +
'CQL_FILTER=COD_SETOR = '+codigo_setor+' and COD_QUADRA='+codigo_quadra+'&' +
'all=' + extent.join(',') + ',EPSG:4326';
},
strategy: ol.loadingstrategy.all
})
});
}else{
my_layer = new ol.layer.Vector({
name: 'my_layer',
visible: true,
style: my_style,
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: function(extent) {
return urlGeoserver +'wfs?service=WFS&' +
'version='+versionGeoserver+'&request=GetFeature&typename=geo:MY_LAYER&' +
'&outputFormat=application/json&srsname=EPSG:4326&' +
'CQL_FILTER=COD_SETOR = '+codigo_setor+' and COD_QUADRA = '+codigo_quadra+' and COD_LOTE='+codigo_lote+'&' +
'all=' + extent.join(',') + ',EPSG:4326';
},
strategy: ol.loadingstrategy.all
})
});
}
return my_layer
}
setLayerLoteFiscal(value_codigo_setor, value_codigo_quadra, value_codigo_lote, show)
map.addLayer(layer_cadastro_lote_fiscal_busca)
//here: I would like to show it in a certain zoom, centered by the layer
I tested to check if there are features on the layer, but it returns 0. This was the code I tested, but it didn't work.
if (my_layer.getSource().getFeatures().length > 0) {
map.getView().fit(my_layer.getExtent(), map.getSize());
}else alert('0')
What is wrong? I am not able to center on the map.