我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.gis.geos.Polygon()。
def test_bounding_box_filter(api_client, parking_area_factory): polygon_1 = Polygon([[10, 40], [20, 40], [20, 50], [10, 50], [10, 40]], srid=4326).transform(3879, clone=True) polygon_2 = Polygon([[30, 50], [40, 50], [40, 60], [30, 60], [30, 50]], srid=4326).transform(3879, clone=True) area_1 = parking_area_factory(geom=MultiPolygon(polygon_1)) area_2 = parking_area_factory(geom=MultiPolygon(polygon_2)) data = get(api_client, list_url) assert data['count'] == 2 assert get_ids_from_results(data['features']) == {area_1.id, area_2.id} data = get(api_client, list_url + '?in_bbox=5,5,85,85') assert data['count'] == 2 assert get_ids_from_results(data['features']) == {area_1.id, area_2.id} data = get(api_client, list_url + '?in_bbox=5,35,25,55') assert data['count'] == 1 assert get_ids_from_results(data['features']) == {area_1.id} data = get(api_client, list_url + '?in_bbox=80,80,85,85') assert data['count'] == 0
def test_bounding_box_filter(api_client, parking_area_factory): polygon_1 = Polygon([[10, 40], [20, 40], [20, 50], [10, 50], [10, 40]], srid=4326).transform(3879, clone=True) polygon_2 = Polygon([[30, 50], [40, 50], [40, 60], [30, 60], [30, 50]], srid=4326).transform(3879, clone=True) area_1 = parking_area_factory(geom=MultiPolygon(polygon_1)) area_2 = parking_area_factory(geom=MultiPolygon(polygon_2)) data = get(api_client, list_url) assert len(data['results']) == 2 assert get_ids_from_results(data['results']) == {area_1.id, area_2.id} data = get(api_client, list_url + '?in_bbox=5,5,85,85') assert len(data['results']) == 2 data = get(api_client, list_url + '?in_bbox=5,35,25,55') assert len(data['results']) == 1 assert get_ids_from_results(data['results']) == {area_1.id} data = get(api_client, list_url + '?in_bbox=80,80,85,85') assert len(data['results']) == 0
def tile(self, lonlat, zoom): """ Returns a Polygon corresponding to the region represented by a fictional Google Tile for the given longitude/latitude pair and zoom level. This tile is used to determine the size of a tile at the given point. """ # The given lonlat is the center of the tile. delta = self._tilesize / 2 # Getting the pixel coordinates corresponding to the # the longitude/latitude. px = self.lonlat_to_pixel(lonlat, zoom) # Getting the lower-left and upper-right lat/lon coordinates # for the bounding box of the tile. ll = self.pixel_to_lonlat((px[0] - delta, px[1] - delta), zoom) ur = self.pixel_to_lonlat((px[0] + delta, px[1] + delta), zoom) # Constructing the Polygon, representing the tile and returning. return Polygon(LinearRing(ll, (ll[0], ur[1]), ur, (ur[0], ll[1]), ll), srid=4326)
def __init__(self, w_lng=180.0, s_lat=90.0, e_lng=-180.0, n_lat=-90.0): """ IMPORTANT: Initialization arguments are ordered w, s, e, n in order to accept arguments from a GEOSGeometry extent, which is a 4-tuple consisting of (xmin, ymin, xmax, ymax). This makes it easy to initialize bounds directly, e.g.: >>> from django.contrib.gis.geos import Polygon >>> polygon = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) >>> bounds = Bounds(*polygon.extent) """ self._n_lat = n_lat self._s_lat = s_lat self._e_lng = e_lng self._w_lng = w_lng # TODO(LH): add validations for lat/lng values
def convert_circle_to_rectangle(point, radius_m): """ (tuple(int or float, int or float), int or float) -> GEOSGeometry Polygon Takes a circle as a (lng, lat) tuple and a radius in meters. Returns the smallest rectangular Polygon that encompasses the circle. """ # reverse the lng, lat order to convert to geopy Point format center = reverse_coordinate_order(point) # create a geopy coordinate calculator for the given distance calculator = vincenty(meters=radius_m) # calculate points at the given distance in the cardinal directions n_pt = calculator.destination(point=center, bearing=0) s_pt = calculator.destination(point=center, bearing=180) e_pt = calculator.destination(point=center, bearing=90) w_pt = calculator.destination(point=center, bearing=270) bounds = Bounds(n_lat=n_pt.latitude, s_lat=s_pt.latitude, e_lng=e_pt.longitude, w_lng=w_pt.longitude) return bounds.bounding_box
def _process_parameters(self, coord, radius_m): """ Helper function to process test parameters through the factor_polygon_into_circles function. """ radius_km = units.meters_to_km(radius_m) polygon = Polygon(coord) points = shapes.factor_polygon_into_circles(polygon, radius_km) # take the generated points and turn them into "circles" (polygons) radius_in_deg = units.convert_meters_to_degrees(radius_m) circles = [Point(point).buffer(radius_in_deg) for point in points] # convert the list of circles into a multipolyon and merge them merged_circles = MultiPolygon(circles).cascaded_union # make sure the merged circles have no holes and completely cover # the original polygon self.assertTrue(merged_circles.num_interior_rings == 0, 'The merged circles had %s holes but should have none' % merged_circles.num_interior_rings) self.assertTrue(merged_circles.prepared.covers(polygon), 'The merged circles do not cover the polygon')
def shape(self): """ Returns a string indicating the feature type. If the feature type is not a Point, Polygon, or Multipolygon, returns 'Other'. """ if isinstance(self.geom, Point): if self.has_buffer(): return 'Circle' else: return 'Point' elif isinstance(self.geom, Polygon): if shapes.is_rectangle(self.geom.exterior_ring): return 'Rectangle' else: return 'Polygon' elif isinstance(self.geom, MultiPolygon): return 'MultiPolygon' else: return 'Other'
def bbox(self): """ If the Location is a Circle, Rectangle, Polygon, or MultiPolygon, returns the smallest rectangle that encompasses the Location's geometry. Otherwise returns None. """ if self.shape is 'Circle': return shapes.convert_circle_to_rectangle(self.geom, self.buffer_m) elif self.shape is'Rectangle': return self.geom elif self.shape is 'Polygon' or self.shape is 'MultiPolygon': return self.geom.envelope else: return None
def polygon_requires_clipping(wgs84_polygon): geom_type = wgs84_polygon.geom_type if geom_type == 'MultiPolygon': polygons = wgs84_polygon.coords elif geom_type == 'Polygon': polygons = [wgs84_polygon.coords] else: raise Exception("Unknown geom_type {0}".format(geom_type)) for polygon in polygons: for t in polygon: for x, y in t: point = Point(x, y) if not uk_multipolygon.contains(point): return True return False # ------------------------------------------------------------------------ # Make sure the output directory exists:
def generate_polygon(): center = generate_point() points = [ Point( center.x + fake.random.uniform(-0.001, 0.001), center.y + fake.random.uniform(-0.001, 0.001), srid=4326, ).transform(3879, clone=True) for _ in range(3) ] points.append(points[0]) return Polygon(points)
def _get_polygons(self, geom): """ Turns the XML containing coordinates into a multipolygon """ polygons = [] for pos in geom.iter('*'): # get leaf nodes. Treat LinearRing and MultiSurface the same way if len(pos) == 0: positions = list(filter(None, pos.text.split(' '))) points = [] points_as_pairs = zip(positions[1::2], positions[::2]) for latitude, longitude in points_as_pairs: points.append(Point(float(latitude), float(longitude))) polygons.append(Polygon(points)) return MultiPolygon(polygons)
def __init__(self, geom): """ Oracle requires that polygon rings are in proper orientation. This affects spatial operations and an invalid orientation may cause failures. Correct orientations are: * Outer ring - counter clockwise * Inner ring(s) - clockwise """ if isinstance(geom, Polygon): self._fix_polygon(geom) elif isinstance(geom, GeometryCollection): self._fix_geometry_collection(geom) self.wkt = geom.wkt self.srid = geom.srid
def _fix_geometry_collection(self, coll): # Fix polygon orientations in geometry collections as described in # __init__() for i, geom in enumerate(coll): if isinstance(geom, Polygon): coll[i] = self._fix_polygon(geom)
def write(self, geom): "Returns the WKB representation of the given geometry." from django.contrib.gis.geos import Polygon geom = self._handle_empty_point(geom) wkb = wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t())) if isinstance(geom, Polygon) and geom.empty: # Fix GEOS output for empty polygon. # See https://trac.osgeo.org/geos/ticket/680. wkb = wkb[:-8] + b'\0' * 4 return six.memoryview(wkb)
def write_hex(self, geom): "Returns the HEXEWKB representation of the given geometry." from django.contrib.gis.geos.polygon import Polygon geom = self._handle_empty_point(geom) wkb = wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t())) if isinstance(geom, Polygon) and geom.empty: wkb = wkb[:-16] + b'0' * 8 return wkb # ### WKBWriter Properties ### # Property for getting/setting the byteorder.
def import_shp(request, shp_name): from django.contrib.gis.gdal import DataSource root = 'C:\\Users\\JohaadienR\\Documents\\Projects\\python-sites\\georef-data-sources\\planetgis\\' # Keep track of all the layers we are adding in layers = ['District Municipalities 2016.kml', 'Local Municipalities 2016.kml', 'Wards 2016.kml', 'Main Places.kml', 'Sub Places.kml'] for layer_name in layers: ds = DataSource(root + layer_name) for item in ds[0]: # Get name and location from layer locality_name = item.get('Name') try: polygon = Polygon(item.geom.coords[1][0]) except GEOSException: continue # Get/create the geographical position, locality name and importer profile gp, created = models.GeographicalPosition.objects.get_or_create(polygon=polygon, precision_m=0) ln, created = models.LocalityName.objects.get_or_create(locality_name=locality_name) au, created = models.Profile.objects.get_or_create(name='Surveyor General') # Get/create the georeference using the above models.GeoReference.objects.get_or_create(locality_name=ln, geographical_position=gp, author=au)
def filter_bbox(self, queryset, value): bbox = [float(coord) for coord in value.split(',')] bbox = Polygon(( bbox[:2], [bbox[0], bbox[3]], bbox[2:], [bbox[2], bbox[1]], bbox[:2] )) return queryset.filter(geom__intersects=bbox)
def create_scene(self): """Get or Create a new Scene object for this path and row.""" scene_date = calendar_date( self.next_scene_name()[9:13], self.next_scene_name()[13:16] ) try: geom = Polygon(get_bounds(self.next_scene_name())) except IndexError: geom = None try: cloud_rate = get_cloud_rate(self.next_scene_name()) except FileNotFoundError: cloud_rate = None return Scene.objects.get_or_create( path=self.path, row=self.row, sat='L8', name=self.next_scene_name(), date=scene_date, status='downloading', geom=geom, cloud_rate=cloud_rate )
def test_download(self): # mock creation_date to 2015-01-01, so we will have a correct date # to download a new scene self.sd.creation_date = date(2015, 1, 1) self.sd.save() downloaded = self.sd.download_new_scene([10, 11]) self.assertEqual(len(downloaded), 2) scene = Scene.objects.get(name='LC82200662015017LGN00') self.assertIsInstance(scene, Scene) bounds = Polygon(((-45.4508, -7.62855), (-43.75824, -7.98923), (-44.12919, -9.73044), (-45.82968, -9.36601), (-45.4508, -7.62855))) self.assertEqual(scene.cloud_rate, 65.28) self.assertEqual(scene.geom, bounds) self.assertEqual(scene.status, 'downloading') self.assertIsInstance( Image.objects.get(name='LC82200662015017LGN00_B10.TIF'), Image ) self.assertIsInstance( Image.objects.get(name='LC82200662015017LGN00_B11.TIF'), Image ) self.assertEqual(self.sd.check_last_scene([10, 11]), []) self.assertEqual(self.sd.last_scene().status, 'downloaded') downloaded = self.sd.check_last_scene([10, 11, 'BQA']) self.assertEqual(len(downloaded), 3) self.assertIsInstance( Image.objects.get(name='LC82200662015017LGN00_BQA.TIF'), Image ) rmtree(downloaded[2][0].replace('/LC82200662015017LGN00_BQA.TIF', '')) self.assertEqual(self.sd2.download_new_scene(['BQA']), [])
def test_geo_scene_pagination_response(self): for i in range(1,21): Scene.objects.create( path='001', row='001', sat='L8', date=date(2015, 2, 2), name='LC80010012015001LGN'.join("%02d" % i ), cloud_rate=21.9, status='downloading', geom=Polygon( [ [-54.159229, -11.804765], [-56.405499, -11.291305], [-55.990002, -9.499491], [-53.755329, -10.006503], [-54.159229, -11.804765] ]) ) self.assertEqual(Scene.objects.count(), 22) response = client.get(reverse('geoscene-listview')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data.get('features')), 20) response = client.get(reverse('geoscene-listview'), {'page': 2}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data.get('features')), 2)