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.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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, get_pointer_arr
  5. from django.contrib.gis.geos.linestring import LinearRing
  6. from django.utils import six
  7. from django.utils.six.moves import range
  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 range(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=(
  85. 'Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings')):
  86. "Helper routine for trying to construct a ring from the given parameter."
  87. if isinstance(param, LinearRing):
  88. return param
  89. try:
  90. ring = LinearRing(param)
  91. return ring
  92. except TypeError:
  93. raise TypeError(msg)
  94. def _set_list(self, length, items):
  95. # Getting the current pointer, replacing with the newly constructed
  96. # geometry, and destroying the old geometry.
  97. prev_ptr = self.ptr
  98. srid = self.srid
  99. self.ptr = self._create_polygon(length, items)
  100. if srid:
  101. self.srid = srid
  102. capi.destroy_geom(prev_ptr)
  103. def _get_single_internal(self, index):
  104. """
  105. Returns the ring at the specified index. The first index, 0, will
  106. always return the exterior ring. Indices > 0 will return the
  107. interior ring at the given index (e.g., poly[1] and poly[2] would
  108. return the first and second interior ring, respectively).
  109. CAREFUL: Internal/External are not the same as Interior/Exterior!
  110. _get_single_internal returns a pointer from the existing geometries for use
  111. internally by the object's methods. _get_single_external returns a clone
  112. of the same geometry for use by external code.
  113. """
  114. if index == 0:
  115. return capi.get_extring(self.ptr)
  116. else:
  117. # Getting the interior ring, have to subtract 1 from the index.
  118. return capi.get_intring(self.ptr, index - 1)
  119. def _get_single_external(self, index):
  120. return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid)
  121. _set_single = GEOSGeometry._set_single_rebuild
  122. _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild
  123. # #### Polygon Properties ####
  124. @property
  125. def num_interior_rings(self):
  126. "Returns the number of interior rings."
  127. # Getting the number of rings
  128. return capi.get_nrings(self.ptr)
  129. def _get_ext_ring(self):
  130. "Gets the exterior ring of the Polygon."
  131. return self[0]
  132. def _set_ext_ring(self, ring):
  133. "Sets the exterior ring of the Polygon."
  134. self[0] = ring
  135. # Properties for the exterior ring/shell.
  136. exterior_ring = property(_get_ext_ring, _set_ext_ring)
  137. shell = exterior_ring
  138. @property
  139. def tuple(self):
  140. "Gets the tuple for each ring in this Polygon."
  141. return tuple(self[i].tuple for i in range(len(self)))
  142. coords = tuple
  143. @property
  144. def kml(self):
  145. "Returns the KML representation of this Polygon."
  146. inner_kml = ''.join("<innerBoundaryIs>%s</innerBoundaryIs>" % self[i + 1].kml
  147. for i in range(self.num_interior_rings))
  148. return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)