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.

polygon.py 6.5KB

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