An even better solution using min/max coords to make the bbox getFeature usable for any direction of dragging and using a button system for having 2 or more layers
So , we create the bbox interaction on our Map ,get the projection (I transform it to EPSG:4326) and give the user his bbox co-ords. After that we do an AJAX call to our server using the Get Feature geoserver command with a bbox in the URI (https://docs.geoserver.org/latest/en/user/tutorials/cql/cql_tutorial.html here's the documentation). Watch out for the CORS configuration on your server (Enabling CORS in GeoServer (jetty)? , thank you for the comment on the original question)
var select = new ol.interaction.Select();
map.addInteraction(select);
var selectedFeatures = select.getFeatures();
var dragBox = new ol.interaction.DragBox({
condition: ol.events.condition.shiftKeyOnly,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 0, 255, 1]
})
})
});
map.addInteraction(dragBox);
var infoBox = document.getElementById('box');
dragBox.on('boxend', function() {
var lonList=[]
var latList=[]
var string = dragBox.getGeometry().getCoordinates();
for(i=0;i<4;i++){
string[0][i]=ol.proj.transform(string[0][i],'EPSG:3857', 'EPSG:4326');
lonList.push(string[0][i][0])
latList.push(string[0][i][1])
}
var minLon=Math.min.apply(Math,lonList)
var minLat=Math.min.apply(Math,latList)
var maxLon=Math.max.apply(Math,lonList)
var maxLat=Math.max.apply(Math,latList)
window.alert("Min Longitude: "+minLon+"\n"+"Max Longitude: "+maxLon+"\n"+"Min Latitude: "+minLat+"\n"+"Max Latitude: "+maxLat)
function getFeature(button,layer){
if(button.checked){
var url= "http://localhost:8080/geoserver/wfs?service=WFS&version=2.0.0&request=GetFeature&typeNames="+ layer +"&srsName=EPSG:4326&maxFeatures=1000000&outputFormat=json&format_options=callback:getJson&bbox="+minLon + "," + minLat + "," + maxLon + "," + maxLat+",EPSG:4326" ;
if(url){
$.ajax({
type:"GET",
url: url,
dataType: 'json',
jsonpCallback: 'getJson',
contentType: 'application/json',
success: function(data){
console.log(data)
}
});
}
};
}
getFeature(lighthousesbtn,"openMapProject:lighthouses_grc");
getFeature(militarygrc,"openMapProject:military_grc");
getFeature(telecom,"openMapProject:telecom_cables_grc");
});