Thursday 19 February 2015

geoserver - No popup on map if no feature is selected


I've got a webmap showing data coming from a Geoserver instance. With better.WMS.js I made it possible to display popups.


Everything works nice except that the map shows popups too where there is no feature selected.


The code is hosted on GitHub. I'll try to put a working map online though one may see the problem clearly. The map shouldn't display a popup window when no feature is selected.



Does anyone has an idea how to fix that?



Answer



You can switch to infoformat=application/json so you will get a json response from Geoserver. Then just check how many features are returned and if features.length>0 is true show the popup otherwise not. For this solution you will have to create a table from the json-response. You could do something like that:


set infoformat in your L.TileLayer.BetterWMS.js:


params = {
request: 'GetFeatureInfo',
service: 'WMS',
srs: 'EPSG:4326',
styles: this.wmsParams.styles,
transparent: this.wmsParams.transparent,

version: this.wmsParams.version,
format: this.wmsParams.format,
bbox: this._map.getBounds().toBBoxString(),
height: size.y,
width: size.x,
layers: this.wmsParams.layers,
query_layers: this.wmsParams.layers,
info_format: 'application/json'
,propertyName:'LAND,DATUM' // only get attributes "Land" and "Name"
};


// Create a function that will return a table from a json response:


function buildpopup(content){

var record;

var info = "
";

for (var i=0 ; i < content.features.length; i++ ){


record = content.features[i];

info += "
"
info += "";
info += "";
info+="
Name:
" + record.properties.name + "
";


if (i!= (content.features.length-1)){
info += "
";

}

}

info += "
"


return info;

}


and use this function while setting the content of the popup:


    showGetFeatureInfo: function (err, latlng, content) {
if (err) {
return;
} // do nothing if there's an error

if (content.features.length>0)
{
// Otherwise show the content in a popup, or something.

L.popup({ maxWidth: 800})
.setLatLng(latlng)
.setContent(buildpopup(content))
.openOn(this._map);
}
else
{
}
}


Screenshot from my working example with json response: enter image description here


EDIT1: added two gists:


html-part: https://gist.github.com/anonymous/aa86f117f1342179f2e3


js-part: https://gist.github.com/anonymous/f6e7dc3d4eff9e0ed62b


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...