I am using OpenLayers 3.9 draw feature to create layers and save them in a PostgreSQL database and publishing them using geoserver so I can use the WMS to display the saved layers.
Whenever the map page is loaded I am generating the following javascript file using a php script which runs a loop and defines all the existing layers (like drw1, drw2, .. ) to get the layers from geoserver and I use ol3-layerswitcher
to list all the layers that are loaded.
var drw1 = new ol.layer.Tile({
title: 'draw_test_1',
source: new ol.source.TileWMS(({
url: 'http://localhost:8080/geoserver/TEST/wms',
params:{
'LAYERS': 'draw_test_1',
'TILED': true
},
serverType: 'geoserver'
})),
});
Currently, I am refreshing the map page whenever a new layer is saved so that the js file gets updated and the new layer will be added and gets displayed in layerswitcher.
I want to save the layer and refresh the layer switcher without reloading the map. I tried using ajax to save the layer and update the js file in background and adding the updated js file again.
<script>
$('#savelayer').click(function() {
$.ajax({
type: 'POST',
url: 'savelyr.php',
data: 'slyrname='+$('#slyrname').val()+'&getdrawn='+$('#getdrawn').val(),
success: function(msg) {
console.log(msg);
}
});
$.ajax({
url: 'maplayers.php',
success: function() {
var s1 = document.createElement("script");
s1.src = "src/ol/map.js";
s1.innerHTML = null;
document.getElementById("scripts").innerHTML = "";
document.getElementById("scripts").appendChild(s1);
console.log("Success 2");
}
});
});
</script>
The js file gets updated and is being added to the map page but I am not sure how to update the layer switcher to show the new layer in the list. I believe that the renderPanel() function in ol3-layerswitcher auto updates the list every time it's closed and opened. But it doesn't seem to work.
So I think the problem is with the way I am adding the js file after saving. Can someone let me know where the problem is or what I need to do to get the layer switcher updated without reloading the page?
After a bit of struggle trying to figure out what the problem is I gave up and modified my code like this. This just defines the new layer and adds it to the map and layer switcher.
var num = 0;
var tmp = "tmp"+num;
var s = "s"+num;
$('#savelayer').click(function() {
var slyrname = $('#slyrname').val();
$.ajax({
type: 'POST',
url: 'savelyr.php',
data: 'slyrname='+$('#slyrname').val()+'&getdrawn='+$('#getdrawn').val(),
success: function(msg) {
console.log(msg);
$.ajax({
url: 'map.php',
success: function() {
var s = document.createElement("script");
s.innerHTML =
"var "+tmp+" = new ol.layer.Tile({"+
"title: '"+slyrname+"',"+
"source: new ol.source.TileWMS({"+
"url: 'http://localhost:8080/geoserver/WS/wms',"+
"params:{'Layers':'"+slyrname+"'}}),"+
"zIndex:'1'});";
document.getElementById("scripts").appendChild(s);
map.addLayer(tmp);
num++;
console.log("Success 2");
}
});
}
});
});
A better approach can still be useful.