这是一个简单的例子。在服务器端:
def get_wfs():
'''
Get data from wfs server. Example url is:
http://192.168.0.1:8080/geoserver/wfs?request=GetFeature&version=1.0.0&service=WFS&typeName=ChistaWS:Chista_new_POIs&maxfeatures=20&srsname=EPSG:4326&outputFormat=json
We can add CQL filter like this:
CQL_FILTER=name LIKE 'A%25'
or
CQL_FILTER=type=1913
'''
cql = ''
if request.vars.cql:
cql = urllib.quote_plus(request.vars.cql)
req = 'GetFeature' # request
version = '1.0.0'
service = 'WFS'
typeName = 'Test:Test_Places'
maxfeatures = 200000
if request.vars.mf:
maxfeatures = request.vars.mf
srsname = 'EPSG:4326'
outputFormat = 'json'
# format_options = 'callback:getLayerFeatures_MY'
wfs_url = '%s?request=%s&version=%s&service=%s&typeName=%s&maxfeatures=%s&srsname=%s&outputFormat=%s' % \
(wfs_server, req, version, service, typeName,\
maxfeatures, srsname, outputFormat)
if cql:
# print cql
wfs_url += '&CQL_FILTER=%s'%cql
# print wfs_url
try:
jsonp = urllib2.urlopen(wfs_url).read() # Get the raw server data
except urllib2.HTTPError:
return 'WFS Server <a target="_new" href="%s">%s</a> is down!' % (wfs_server, wfs_server)
# return jsonp
# try:
# apijson = jsonp[ jsonp.index("(") + 1 : jsonp.rindex(")") ]
# except ValueError:
apijson = jsonp
try:
data = sj.loads(apijson)
except sj.JSONDecodeError:
return 'Can not parse data. No JSON! here is the data: <pre>%s</pre>' % apijson
# return data
features =[{
'name':i['properties']['name'],
'type':i['properties']['type'],
'coordinates':i['geometry']['coordinates'],
} for i in data['features']]
# features =[i for i in data['features']]
# return dict(features=features)
return {'result':features, 'length':len(features)}
并在客户端使用jQuery:
$.ajax({
dataType : 'json',
url: wfsurl,
success : function (response) {
if (response.length>0){
$('#'+subitem).empty();
for (var i = 0, len = response.length; i < len; i++) {
name = response.result[i].name;
lng = response.result[i].coordinates[0];
lat = response.result[i].coordinates[1];
// console.log(name, lng, lat)
html = '<li class="li-subitem"><a onclick="lazyview($(this));" lat="'+lat+'" lng="'+lng+'">'+name+'</a></li>';
$('#'+subitem).append(html);
}}
else{
$('#'+subitem).toggle(100);
}}});