This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
WFSOverlayServer.py
204 lines (180 loc) · 6.64 KB
/
WFSOverlayServer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
from projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
GMLNS = "http://www.opengis.net/gml"
try:
from pyproj import Proj
from lxml.etree import ElementTree as ET
except:
# try:
from xml.etree import ElementTree as ET
# except:
# pass
class WFSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap = 'Roadmap') # default
type = "wfs" # TODO: replace handling in mapviewer with action handlers in the overlay class
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def load(self, url):
# read from internet
blocksize = 4096
self.progress_callback(0)
fd = urlopen(url)
idata = fd.read(blocksize)
loaded = blocksize
while True:
bdata = fd.read(blocksize)
if not bdata: break
loaded += blocksize
if self.progress_callback:
self.progress_callback(loaded)
idata += bdata
fd.close()
self.progress_callback(-1)
return idata
def findGeometry(self, elem):
geoms = elem.find("{%s}Point" % GMLNS)
if geoms is not None:
return geoms
geoms = elem.find("{%s}LinearRing" % GMLNS)
if geoms is not None:
return geoms
for c in elem.getchildren():
geom = self.findGeometry(c)
if geom is not None:
return geom
def findGeometries(self, members):
geoms = []
for m in members:
geom = self.findGeometry(m)
if geom is not None:
geoms.append(geom)
return geoms
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1])
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
xml = self.load('http://' + self.provider_host + url)
tree = ET.fromstring(xml)
members = tree.findall("{%s}featureMember" % GMLNS)
self.geometries = self.findGeometries(members)
self.cache[key] = self.geometries
return self.geometries
except Exception,e:
Logger.error('OverlayServer could not find (or read) WFS from %s [%s]' % (url, e))
image = None
def getInfoText(self, member):
fields = member.getchildren()[0].getchildren()
info = ""
for field in fields:
if field.text is not None and field.text.strip() != "":
info += "%s: %s\n" % (field.tag[field.tag.index("}")+1:], field.text)
return info
def getInfo(self, lat, lon, epsilon):
try:
url = self.geturl(lat-epsilon, lon-epsilon, lat+epsilon, lon+epsilon)
except:
return None
try:
xml = self.load('http://' + self.provider_host + url)
tree = ET.fromstring(xml)
member = tree.find("{%s}featureMember" % GMLNS)
if member is not None:
infotext = self.getInfoText(member)
return infotext
except Exception,e:
Logger.error('OverlayServer could not find (or read) WFS from %s [%s]' % (url, e))
return None
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x,y
def co_to_ll(self,x,y):
if self.customBounds:
l, m = custom_to_latlon(x, y, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&bbox=%f,%f,%f,%f" % (x1, y1, x2, y2)
except RuntimeError, e:
return None
def parseFeature(self, feature, data):
try:
name = feature.find("Name").text
title = feature.find("Title").text
except:
name = None
title = None
srss = feature.findall("DefaultSRS")
if name:# and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides feature %s in projections %s" % (self.provider_host, name, data[name])
def initFromGetCapabilities(self, host, baseurl, feature = None, index = 0, srs = None):
self.debug = (feature == None) and (index == 0)
# GetCapabilities (Features + SRS)
capabilities = urlopen(host + baseurl + "?SERVICE=WFS&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
features = tree.findall("FeatureType") #TODO: proper parsing of cascading layers and their SRS
data = {}
for f in features:
self.parseFeature(f, data)
# Choose Feature and SRS by (alphabetical) index
if feature is None:
feature = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[feature])[0]
except:
pass
print "Displaying from %s/%s: feature %s in SRS %s." % (host, baseurl, feature, srs)
# generate tile URL and init projection by EPSG code
self.feature = feature
self.url = baseurl + "?typeName=namespace:%s&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&maxFeatures=50" % (feature)
self.isPGoogle = False
self.isPLatLon = False
if srs=="EPSG:4326":
self.isPLatLon = True
elif srs=="EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass