You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wkt.py 1.9 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """
  2. Utilities for manipulating Geometry WKT.
  3. """
  4. from django.utils import six
  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. >>> from django.contrib.gis.geos import Point
  11. >>> pnt = Point(5, 23)
  12. >>> pnt.wkt
  13. 'POINT (5.0000000000000000 23.0000000000000000)'
  14. >>> precision_wkt(pnt, 1)
  15. 'POINT (5.0 23.0)'
  16. If the precision is a string, it must be valid Python format string
  17. (e.g., '%20.7f') -- thus, you should know what you're doing.
  18. """
  19. if isinstance(prec, int):
  20. num_fmt = '%%.%df' % prec
  21. elif isinstance(prec, six.string_types):
  22. num_fmt = prec
  23. else:
  24. raise TypeError
  25. # TODO: Support 3D geometries.
  26. coord_fmt = ' '.join([num_fmt, num_fmt])
  27. def formatted_coords(coords):
  28. return ','.join(coord_fmt % c[:2] for c in coords)
  29. def formatted_poly(poly):
  30. return ','.join('(%s)' % formatted_coords(r) for r in poly)
  31. def formatted_geom(g):
  32. gtype = str(g.geom_type).upper()
  33. yield '%s(' % gtype
  34. if gtype == 'POINT':
  35. yield formatted_coords((g.coords,))
  36. elif gtype in ('LINESTRING', 'LINEARRING'):
  37. yield formatted_coords(g.coords)
  38. elif gtype in ('POLYGON', 'MULTILINESTRING'):
  39. yield formatted_poly(g)
  40. elif gtype == 'MULTIPOINT':
  41. yield formatted_coords(g.coords)
  42. elif gtype == 'MULTIPOLYGON':
  43. yield ','.join('(%s)' % formatted_poly(p) for p in g)
  44. elif gtype == 'GEOMETRYCOLLECTION':
  45. yield ','.join(''.join(wkt for wkt in formatted_geom(child)) for child in g)
  46. else:
  47. raise TypeError
  48. yield ')'
  49. return ''.join(wkt for wkt in formatted_geom(geom))