I'm trying to configure the Twitter Typeahead library to work with a GeoServer WFS layer, so I can create an auto-complete feature search function.
Typeahead has the Bloodhound suggestion engine, which can work with a remote data source. There's a good working example at http://jsfiddle.net/Fresh/bbzt9hcr/ where the transform
function is used to convert the nested JSON response into an array which is displayed in the Typeahead dropdown.
I believe that it's necessary to use JSONP and a callback function in order to avoid cross-origin issues in GeoServer (please correct me if I'm wrong) so I'm using the following code to achieve this:
var parameters = {
format_options: "callback:typeaheadCallback",
service: "WFS",
version: "1.0.0",
request: "GetFeature",
typeName: "repairernames",
outputFormat: "text/javascript",
propertyName: "repairername",
CQL_FILTER: "repairername like 'QUERY%'"
}
var repairers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
wildcard: '%QUERY',
url: 'http://localhost/geoserver/blah/wfs?' + jQuery.param(parameters),
transform: function (result) {
return $.map(result.features, function (feature) {
return {
value: feature.properties.repairername
};
});
},
prepare: function(query, settings) {
settings.dataType = "jsonp"
settings.url = settings.url.replace('QUERY', query)
return settings;
}
}
});
function typeaheadCallback(json){
console.log("Typeahead callback response: ", json);
return json;
}
The change compared to the working demo is the new prepare
function (described here) which tells Bloodhound/Typeahead to use JSONP, and the callback typeaheadCallback
which is specified in the parameters.
Via the debugger I can see that the request to GeoServer is successfully implemented, and the console.log
in the typeaheadCallback
shows that valid values are returned as JSON.
The problem is that the transform
function is never called, so the returned JSON object from GeoServer isn't transformed, and therefore isn't sent to the Typeahead dropdown menu, which therefore doesn't display results.
How can I configure Typeahead and Bloodhound to work with a GeoServer WFS layer?