polygon.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. from ctypes import c_uint, byref
  2. from django.contrib.gis.geos.geometry import GEOSGeometry
  3. from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR
  4. from django.contrib.gis.geos.linestring import LinearRing
  5. from django.contrib.gis.geos import prototypes as capi
  6. from django.utils import six
  7. from django.utils.six.moves import xrange
  8. class Polygon(GEOSGeometry):
  9. _minlength = 1
  10. def __init__(self, *args, **kwargs):
  11. """
  12. Initializes on an exterior ring and a sequence of holes (both
  13. instances may be either LinearRing instances, or a tuple/list
  14. that may be constructed into a LinearRing).
  15. Examples of initialization, where shell, hole1, and hole2 are
  16. valid LinearRing geometries:
  17. >>> from django.contrib.gis.geos import LinearRing, Polygon
  18. >>> shell = hole1 = hole2 = LinearRing()
  19. >>> poly = Polygon(shell, hole1, hole2)
  20. >>> poly = Polygon(shell, (hole1, hole2))
  21. >>> # Example where a tuple parameters are used:
  22. >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)),
  23. ... ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))
  24. """
  25. if not args:
  26. raise TypeError('Must provide at least one LinearRing, or a tuple, to initialize a Polygon.')
  27. # Getting the ext_ring and init_holes parameters from the argument list
  28. ext_ring = args[0]
  29. init_holes = args[1:]
  30. n_holes = len(init_holes)
  31. # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility]
  32. if n_holes == 1 and isinstance(init_holes[0], (tuple, list)):
  33. if len(init_holes[0]) == 0:
  34. init_holes = ()
  35. n_holes = 0
  36. elif isinstance(init_holes[0][0], LinearRing):
  37. init_holes = init_holes[0]
  38. n_holes = len(init_holes)
  39. polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes)
  40. super(Polygon, self).__init__(polygon, **kwargs)
  41. def __iter__(self):
  42. "Iterates over each ring in the polygon."
  43. for i in xrange(len(self)):
  44. yield self[i]
  45. def __len__(self):
  46. "Returns the number of rings in this Polygon."
  47. return self.num_interior_rings + 1
  48. @classmethod
  49. def from_bbox(cls, bbox):
  50. "Constructs a Polygon from a bounding box (4-tuple)."
  51. x0, y0, x1, y1 = bbox
  52. for z in bbox:
  53. if not isinstance(z, six.integer_types + (float,)):
  54. return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' %
  55. (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))
  56. return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))
  57. ### These routines are needed for list-like operation w/ListMixin ###
  58. def _create_polygon(self, length, items):
  59. # Instantiate LinearRing objects if necessary, but don't clone them yet
  60. # _construct_ring will throw a TypeError if a parameter isn't a valid ring
  61. # If we cloned the pointers here, we wouldn't be able to clean up
  62. # in case of error.
  63. rings = []
  64. for r in items:
  65. if isinstance(r, GEOM_PTR):
  66. rings.append(r)
  67. else:
  68. rings.append(self._construct_ring(r))
  69. shell = self._clone(rings.pop(0))
  70. n_holes = length - 1
  71. if n_holes:
  72. holes = get_pointer_arr(n_holes)
  73. for i, r in enumerate(rings):
  74. holes[i] = self._clone(r)
  75. holes_param = byref(holes)
  76. else:
  77. holes_param = None
  78. return capi.create_polygon(shell, holes_param, c_uint(n_holes))
  79. def _clone(self, g):
  80. if isinstance(g, GEOM_PTR):
  81. return capi.geom_clone(g)
  82. else:
  83. return capi.geom_clone(g.ptr)
  84. def _construct_ring(self, param, msg='Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'):
  85. "Helper routine for trying to construct a ring from the given parameter."
  86. if isinstance(param, LinearRing):
  87. return param
  88. try:
  89. ring = LinearRing(param)
  90. return ring
  91. except TypeError:
  92. raise TypeError(msg)
  93. def _set_list(self, length, items):
  94. # Getting the current pointer, replacing with the newly constructed
  95. # geometry, and destroying the old geometry.
  96. prev_ptr = self.ptr
  97. srid = self.srid
  98. self.ptr = self._create_polygon(length, items)
  99. if srid:
  100. self.srid = srid
  101. capi.destroy_geom(prev_ptr)
  102. def _get_single_internal(self, index):
  103. """
  104. Returns the ring at the specified index. The first index, 0, will
  105. always return the exterior ring. Indices > 0 will return the
  106. interior ring at the given index (e.g., poly[1] and poly[2] would
  107. return the first and second interior ring, respectively).
  108. CAREFUL: Internal/External are not the same as Interior/Exterior!
  109. _get_single_internal returns a pointer from the existing geometries for use
  110. internally by the object's methods. _get_single_external returns a clone
  111. of the same geometry for use by external code.
  112. """
  113. if index == 0:
  114. return capi.get_extring(self.ptr)
  115. else:
  116. # Getting the interior ring, have to subtract 1 from the index.
  117. return capi.get_intring(self.ptr, index - 1)
  118. def _get_single_external(self, index):
  119. return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid)
  120. _set_single = GEOSGeometry._set_single_rebuild
  121. _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild
  122. #### Polygon Properties ####
  123. @property
  124. def num_interior_rings(self):
  125. "Returns the number of interior rings."
  126. # Getting the number of rings
  127. return capi.get_nrings(self.ptr)
  128. def _get_ext_ring(self):
  129. "Gets the exterior ring of the Polygon."
  130. return self[0]
  131. def _set_ext_ring(self, ring):
  132. "Sets the exterior ring of the Polygon."
  133. self[0] = ring
  134. # Properties for the exterior ring/shell.
  135. exterior_ring = property(_get_ext_ring, _set_ext_ring)
  136. shell = exterior_ring
  137. @property
  138. def tuple(self):
  139. "Gets the tuple for each ring in this Polygon."
  140. return tuple(self[i].tuple for i in xrange(len(self)))
  141. coords = tuple
  142. @property
  143. def kml(self):
  144. "Returns the KML representation of this Polygon."
  145. inner_kml = ''.join("<innerBoundaryIs>%s</innerBoundaryIs>" % self[i + 1].kml
  146. for i in xrange(self.num_interior_rings))
  147. return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)