PageRenderTime 30ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/gis/utils/wkt.py

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