|
0
|
1 |
""" |
|
|
2 |
Utilities for manipulating Geometry WKT. |
|
|
3 |
""" |
|
|
4 |
|
|
|
5 |
def precision_wkt(geom, prec): |
|
|
6 |
""" |
|
|
7 |
Returns WKT text of the geometry according to the given precision (an |
|
|
8 |
integer or a string). If the precision is an integer, then the decimal |
|
|
9 |
places of coordinates WKT will be truncated to that number: |
|
|
10 |
|
|
|
11 |
>>> pnt = Point(5, 23) |
|
|
12 |
>>> pnt.wkt |
|
|
13 |
'POINT (5.0000000000000000 23.0000000000000000)' |
|
|
14 |
>>> precision(geom, 1) |
|
|
15 |
'POINT (5.0 23.0)' |
|
|
16 |
|
|
|
17 |
If the precision is a string, it must be valid Python format string |
|
|
18 |
(e.g., '%20.7f') -- thus, you should know what you're doing. |
|
|
19 |
""" |
|
|
20 |
if isinstance(prec, int): |
|
|
21 |
num_fmt = '%%.%df' % prec |
|
|
22 |
elif isinstance(prec, basestring): |
|
|
23 |
num_fmt = prec |
|
|
24 |
else: |
|
|
25 |
raise TypeError |
|
|
26 |
|
|
|
27 |
# TODO: Support 3D geometries. |
|
|
28 |
coord_fmt = ' '.join([num_fmt, num_fmt]) |
|
|
29 |
|
|
|
30 |
def formatted_coords(coords): |
|
|
31 |
return ','.join([coord_fmt % c[:2] for c in coords]) |
|
|
32 |
|
|
|
33 |
def formatted_poly(poly): |
|
|
34 |
return ','.join(['(%s)' % formatted_coords(r) for r in poly]) |
|
|
35 |
|
|
|
36 |
def formatted_geom(g): |
|
|
37 |
gtype = str(g.geom_type).upper() |
|
|
38 |
yield '%s(' % gtype |
|
|
39 |
if gtype == 'POINT': |
|
|
40 |
yield formatted_coords((g.coords,)) |
|
|
41 |
elif gtype in ('LINESTRING', 'LINEARRING'): |
|
|
42 |
yield formatted_coords(g.coords) |
|
|
43 |
elif gtype in ('POLYGON', 'MULTILINESTRING'): |
|
|
44 |
yield formatted_poly(g) |
|
|
45 |
elif gtype == 'MULTIPOINT': |
|
|
46 |
yield formatted_coords(g.coords) |
|
|
47 |
elif gtype == 'MULTIPOLYGON': |
|
|
48 |
yield ','.join(['(%s)' % formatted_poly(p) for p in g]) |
|
|
49 |
elif gtype == 'GEOMETRYCOLLECTION': |
|
|
50 |
yield ','.join([''.join([wkt for wkt in formatted_geom(child)]) for child in g]) |
|
|
51 |
else: |
|
|
52 |
raise TypeError |
|
|
53 |
yield ')' |
|
|
54 |
|
|
|
55 |
return ''.join([wkt for wkt in formatted_geom(geom)]) |