Python django.contrib.gis.geos.Polygon() Examples

The following are 30 code examples of django.contrib.gis.geos.Polygon(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.gis.geos , or try the search function .
Example #1
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_geom_field_dim(self):
        Neighborhood = self.current_state.apps.get_model('gis', 'Neighborhood')
        p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
        Neighborhood.objects.create(name='TestDim', geom=MultiPolygon(p1, p1))
        # Add 3rd dimension.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 3}
        )
        self.assertTrue(Neighborhood.objects.first().geom.hasz)
        # Rewind to 2 dimensions.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 2}
        )
        self.assertFalse(Neighborhood.objects.first().geom.hasz) 
Example #2
Source File: utils.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def chop_geom(multipolygon, fraction):
    """
        Transforms each point fraction the distance to the geometry's centroid to form a smaller geometry
    :param geom:
    :return: a multipolygon reduced by the fraction from the original
    """

    def transform_polygon(polygon):
        def transform_linear_ring(linear_ring):
            centroid = polygon.centroid
            return LinearRing(
                map(lambda point: to_tuple(LineString((point, centroid)).interpolate(fraction, normalized=True)),
                    linear_ring))

        linear_rings = map(lambda linear_ring: transform_linear_ring(linear_ring), polygon)
        if len(linear_rings) > 1:
            return Polygon(linear_rings[0], [linear_rings[1:]])
        else:
            return Polygon(linear_rings[0], [])

    return MultiPolygon(map(lambda polygon: transform_polygon(polygon), multipolygon)) 
Example #3
Source File: utils.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def chop_geom(multipolygon, fraction):
    """
        Transforms each point fraction the distance to the geometry's centroid to form a smaller geometry
    :param geom:
    :return: a multipolygon reduced by the fraction from the original
    """

    def transform_polygon(polygon):
        def transform_linear_ring(linear_ring):
            centroid = polygon.centroid
            return LinearRing(
                map(lambda point: to_tuple(LineString((point, centroid)).interpolate(fraction, normalized=True)),
                    linear_ring))

        linear_rings = map(lambda linear_ring: transform_linear_ring(linear_ring), polygon)
        if len(linear_rings) > 1:
            return Polygon(linear_rings[0], [linear_rings[1:]])
        else:
            return Polygon(linear_rings[0], [])

    return MultiPolygon(map(lambda polygon: transform_polygon(polygon), multipolygon)) 
Example #4
Source File: geo_inheritance_manager.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def extent_polygon(self):
        """
            Convert extent into something more useful--a simple geos polygon
        """
        try:
            # This seems to raise if no rows exist
            extent = self.extent()
        except:
            return None
        bounds = Polygon((
            (extent[0], extent[1]),
            (extent[0], extent[3]),
            (extent[2], extent[3]),
            (extent[2], extent[1]),
            (extent[0], extent[1]),
        ))
        return bounds 
Example #5
Source File: zoom.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: test_models.py    From scale with Apache License 2.0 6 votes vote down vote up
def test_country_data(self):
        """Tests adding a border and country intersection calculation."""
        testborder = geos.Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)))
        testborder2 = geos.Polygon(((11, 0), (11, 8), (19, 8), (19, 0), (11, 0)))
        testborder3 = geos.Polygon(((11, 11), (11, 15), (15, 15), (15, 11), (11, 11)))
        testeffective = datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=utc)
        CountryData.objects.create(name='Test Country', fips='TC', gmi='TCY', iso2='TC', iso3='TCY', iso_num=42,
                                   border=testborder, effective=testeffective)
        CountryData.objects.create(name='Test Country 2', fips='TT', gmi='TCT', iso2='TT', iso3='TCT', iso_num=43,
                                   border=testborder2, effective=testeffective)
        CountryData.objects.create(name='Test Country 3', fips='TH', gmi='TCH', iso2='TH', iso3='TCH', iso_num=44,
                                   border=testborder3, effective=testeffective)
        ws = storage_test_utils.create_workspace(name='test', base_url='http://localhost')
        scale_file = storage_test_utils.create_file(file_name='test.txt', workspace=ws)
        with transaction.atomic():
            scale_file.geometry = geos.Polygon(((5, 5), (5, 10), (12, 10), (12, 5), (5, 5)))
            scale_file.set_countries()
            scale_file.save()
        tmp = [c.iso2 for c in scale_file.countries.all()]
        self.assertEqual(len(tmp), 2)
        self.assertIn('TC', tmp)
        self.assertIn('TT', tmp) 
Example #7
Source File: utils.py    From scale with Apache License 2.0 6 votes vote down vote up
def create_country(name=None, fips='TT', gmi='TT', iso2='TT', iso3='TST', iso_num=0, border=None, effective=None):
    """Creates a country data model for unit testing

    :returns: The file model
    :rtype: :class:`storage.models.CountryData`
    """
    if not name:
        global COUNTRY_NAME_COUNTER
        name = 'test-country-%i' % COUNTRY_NAME_COUNTER
        COUNTRY_NAME_COUNTER += 1
    if not border:
        border = geos.Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)))
    if not effective:
        effective = timezone.now()

    return CountryData.objects.create(name=name, fips=fips, gmi=gmi, iso2=iso2, iso3=iso3, iso_num=iso_num,
                                      border=border, effective=effective) 
Example #8
Source File: zoom.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: models.py    From gazetteer with MIT License 6 votes vote down vote up
def find(self, bbox=None, text=None, adm1=None, adm2=None, is_primary=True, threshold=0.5, srid=4326):
        qset = self.get_query_set().filter(is_primary=is_primary)
        if bbox:
            (minx, miny, maxx, maxy) = bbox
            bbox = Polygon(((minx,miny),(minx,maxy),(maxx,maxy),(maxx,miny),(minx,miny)),srid=srid)
            if srid != 4326: bbox.transform(4326) # convert to lon/lat
            qset = qset.filter(geometry__bboverlaps=bbox)
        if text:
            self.set_threshold(threshold)
            # use the pg_trgm index
            qset = qset.extra(select={"similarity":"similarity(preferred_name, %s)"},
                              select_params=[text],
                              where=["preferred_name %% %s"],
                              params=[text],
                              order_by=["-similarity"])
        if adm1: qset = qset.filter(admin1__exact=adm1)
        if adm2: qset = qset.filter(admin2__exact=adm2)
        return qset 
Example #10
Source File: test_serializers.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_geometry_field_option(self):
        """
        When a model has several geometry fields, the 'geometry_field' option
        can be used to specify the field to use as the 'geometry' key.
        """
        MultiFields.objects.create(
            city=City.objects.first(), name='Name', point=Point(5, 23),
            poly=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))

        geojson = serializers.serialize('geojson', MultiFields.objects.all())
        geodata = json.loads(geojson)
        self.assertEqual(geodata['features'][0]['geometry']['type'], 'Point')

        geojson = serializers.serialize(
            'geojson',
            MultiFields.objects.all(),
            geometry_field='poly'
        )
        geodata = json.loads(geojson)
        self.assertEqual(geodata['features'][0]['geometry']['type'], 'Polygon')

        # geometry_field is considered even if not in fields (#26138).
        geojson = serializers.serialize(
            'geojson',
            MultiFields.objects.all(),
            geometry_field='poly',
            fields=('city',)
        )
        geodata = json.loads(geojson)
        self.assertEqual(geodata['features'][0]['geometry']['type'], 'Polygon') 
Example #11
Source File: test_expressions.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_geography_value(self):
        p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))
        area = City.objects.annotate(a=functions.Area(Value(p, GeometryField(srid=4326, geography=True)))).first().a
        self.assertAlmostEqual(area.sq_km, 12305.1, 0) 
Example #12
Source File: feeds.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def item_geometry(self, item):
        from django.contrib.gis.geos import Polygon
        return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))


# The feed dictionary to use for URLs. 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_3d_polygons(self):
        """
        Test the creation of polygon 3D models.
        """
        self._load_polygon_data()
        p3d = Polygon3D.objects.get(name='3D BBox')
        self.assertTrue(p3d.poly.hasz)
        self.assertIsInstance(p3d.poly, Polygon)
        self.assertEqual(p3d.poly.srid, 32140) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_3d_polygons(self):
        """
        Test the creation of polygon 3D models.
        """
        self._load_polygon_data()
        p3d = Polygon3D.objects.get(name='3D BBox')
        self.assertTrue(p3d.poly.hasz)
        self.assertIsInstance(p3d.poly, Polygon)
        self.assertEqual(p3d.poly.srid, 32140) 
Example #15
Source File: test_expressions.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_multiple_annotation(self):
        multi_field = MultiFields.objects.create(
            point=Point(1, 1),
            city=City.objects.get(name='Houston'),
            poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))),
        )
        qs = City.objects.values('name').annotate(
            distance=Min(functions.Distance('multifields__point', multi_field.city.point)),
        ).annotate(count=Count('multifields'))
        self.assertTrue(qs.first()) 
Example #16
Source File: test_expressions.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_geography_value(self):
        p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))
        area = City.objects.annotate(a=functions.Area(Value(p, GeometryField(srid=4326, geography=True)))).first().a
        self.assertAlmostEqual(area.sq_km, 12305.1, 0) 
Example #17
Source File: test_serializers.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_geometry_field_option(self):
        """
        When a model has several geometry fields, the 'geometry_field' option
        can be used to specify the field to use as the 'geometry' key.
        """
        MultiFields.objects.create(
            city=City.objects.first(), name='Name', point=Point(5, 23),
            poly=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))

        geojson = serializers.serialize('geojson', MultiFields.objects.all())
        geodata = json.loads(geojson)
        self.assertEqual(geodata['features'][0]['geometry']['type'], 'Point')

        geojson = serializers.serialize(
            'geojson',
            MultiFields.objects.all(),
            geometry_field='poly'
        )
        geodata = json.loads(geojson)
        self.assertEqual(geodata['features'][0]['geometry']['type'], 'Polygon')

        # geometry_field is considered even if not in fields (#26138).
        geojson = serializers.serialize(
            'geojson',
            MultiFields.objects.all(),
            geometry_field='poly',
            fields=('city',)
        )
        geodata = json.loads(geojson)
        self.assertEqual(geodata['features'][0]['geometry']['type'], 'Polygon') 
Example #18
Source File: feeds.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def item_geometry(self, item):
        from django.contrib.gis.geos import Polygon
        return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))


# The feed dictionary to use for URLs. 
Example #19
Source File: test_expressions.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_multiple_annotation(self):
        multi_field = MultiFields.objects.create(
            point=Point(1, 1),
            city=City.objects.get(name='Houston'),
            poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))),
        )
        qs = City.objects.values('name').annotate(
            distance=Min(functions.Distance('multifields__point', multi_field.city.point)),
        ).annotate(count=Count('multifields'))
        self.assertTrue(qs.first()) 
Example #20
Source File: adapter.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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) 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def _load_polygon_data(self):
        bbox_wkt, bbox_z = bbox_data
        bbox_2d = GEOSGeometry(bbox_wkt, srid=32140)
        bbox_3d = Polygon(tuple((x, y, z) for (x, y), z in zip(bbox_2d[0].coords, bbox_z)), srid=32140)
        Polygon2D.objects.create(name='2D BBox', poly=bbox_2d)
        Polygon3D.objects.create(name='3D BBox', poly=bbox_3d) 
Example #22
Source File: adapter.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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 
Example #23
Source File: sacog_config_entities.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def regions(self, region_keys=None, class_scope=None):
        return FixtureList([
            {
                'key': 'sac_cnty',
                'name': 'Sacramento County',
                'description': 'Sacramento County',
                'bounds': MultiPolygon([Polygon((
                    (-122.719, 37.394),  # bottom left
                    (-122.719, 38.059),  # top left
                    (-121.603, 38.059),  # top right
                    (-121.603, 37.394),  # bottom right
                    (-122.719, 37.394),  # bottom leftsample_config_entities
                ))])
            },
        ]).matching_keys(key=region_keys).matching_scope(class_scope=class_scope) 
Example #24
Source File: application_initialization.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def initialize_global_config(**kwargs):
    global_bounds = MultiPolygon(
        [Polygon((
            (settings.DEFAULT_SRID_BOUNDS[1], settings.DEFAULT_SRID_BOUNDS[1]),  # bottom left
            (settings.DEFAULT_SRID_BOUNDS[0], settings.DEFAULT_SRID_BOUNDS[3]),  # top left
            (settings.DEFAULT_SRID_BOUNDS[2], settings.DEFAULT_SRID_BOUNDS[3]),  # top right
            (settings.DEFAULT_SRID_BOUNDS[2], settings.DEFAULT_SRID_BOUNDS[1]),  # bottom right
            (settings.DEFAULT_SRID_BOUNDS[1], settings.DEFAULT_SRID_BOUNDS[1]),  # bottom left
        ))],
        srid=settings.DEFAULT_SRID
    )

    # Initialize global policy configuration. TODO, this needs to be more sophisticated
    initialize_policies()

    limit_to_classes = kwargs.get('limit_to_classes', [GlobalConfig]) \
        if kwargs.get('limit_to_classes', [GlobalConfig]) else [GlobalConfig]
    # Optionally disable post-save presentation
    if kwargs.get('no_post_save_publishing'):
        GlobalConfig._no_post_save_publishing = True
    # Create and persist the singleton GlobalConfig
    global_config, created, updated = GlobalConfig.objects.update_or_create(
        key=Keys.GLOBAL_CONFIG_KEY,
        defaults=dict(
            name=Keys.GLOBAL_CONFIG_NAME,
            bounds=global_bounds
        )
    ) if \
        GlobalConfig in limit_to_classes else \
        (GlobalConfig.objects.get(), False, False)
    if kwargs.get('no_post_save_publishing'):
        GlobalConfig._no_post_save_publishing = False

    return global_config 
Example #25
Source File: test_views.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_polygon_equal(self, d):
        g = geos.Polygon(d['features'][0]['geometry']['coordinates'][0])
        g.srid = self.g.srid
        return g.equals_exact(self.g, self.tolerance) 
Example #26
Source File: test_views.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.geometry = {'type': 'Polygon',
                         'coordinates': [[ [14.14, 50.21],
                                           [14.89, 50.20],
                                           [14.39, 49.76],
                                           [14.14, 50.21] ]]}
        Location.create(name='Prague', geom=self.geometry)
        self.g = Location.objects.first().geom
        self.tolerance = .0000001
        self.url = '/vectiles/10/553/347' 
Example #27
Source File: test_importers.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def _run_import_test(self, filename):
        importer = csv.CSVImporter(
            project=self.project, path=self.path + filename)
        config = {
            'file': self.path + filename,
            'entity_types': ['SU', 'PT'],
            'party_name_field': 'name_of_hh',
            'party_type_field': 'party_type',
            'location_type_field': 'location_type',
            'geometry_field': 'location_geometry',
            'attributes': self.attributes,
            'project': self.project,
            'allowed_tenure_types': [t[0] for t in TENURE_RELATIONSHIP_TYPES],
            'allowed_location_types': [choice[0] for choice in TYPE_CHOICES]
        }
        importer.import_data(config)

        assert Party.objects.all().count() == 10
        assert SpatialUnit.objects.all().count() == 10
        assert TenureRelationship.objects.all().count() == 10

        su1 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224045'}).first()
        su2 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224033'}).first()
        su3 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647225965'}).first()
        su4 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224043'}).first()
        su5 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224044'}).first()
        su6 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224185'}).first()

        assert su1.geometry.geom_type == 'Point'
        assert su2.geometry.geom_type == 'LineString'
        assert su3.geometry.geom_type == 'Polygon'
        assert su4.geometry.geom_type == 'MultiPoint'
        assert su5.geometry.geom_type == 'MultiLineString'
        assert su6.geometry.geom_type == 'MultiPolygon' 
Example #28
Source File: models.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def refresh_area(sender, instance, **kwargs):
    """ Ensure DB-generated area is set on instance """
    from django.contrib.gis.geos import MultiPolygon, Polygon
    geom = instance.geometry
    if not isinstance(geom, (MultiPolygon, Polygon)):
        return
    qs = type(instance)._default_manager.filter(id=instance.id)
    instance.area = qs.values_list('area', flat=True)[0] 
Example #29
Source File: models.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_extent(sender, instance, **kwargs):
    geom = instance.geometry
    # Store 'POLYGON EMPTY' data as null to avoid libgeos bug
    # (https://trac.osgeo.org/geos/ticket/680)
    # TODO: Rm this check when we're using Django 1.11+ or libgeos 3.6.1+
    # https://github.com/django/django/commit/b90d72facf1e4294df1c2e6b51b26f6879bf2992#diff-181a3ea304dfaf57f1e1d680b32d2b76R248
    from django.contrib.gis.geos import Polygon
    if isinstance(geom, Polygon) and geom.empty:
        instance.geometry = None
    if geom and not geom.empty:
        reassign_spatial_geometry(instance) 
Example #30
Source File: models.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def reassign_spatial_geometry(instance):
    coords = list(instance.geometry.coords)
    if type(coords[0]) == float:
        coords = [coords]
    else:
        while (type(coords[0][0]) != float):
            coords = coords[0]
        coords = [list(x) for x in coords]
    for point in coords:
        if point[0] >= -180 and point[0] <= 180:
            return
    while coords[0][0] < -180:
        for point in coords:
            point[0] += 360
    while coords[0][0] > 180:
        for point in coords:
            point[0] -= 360
    geometry = []
    for point in coords:
        latlng = [point[0], point[1]]
        geometry.append(tuple(latlng))
    if len(geometry) > 1:
        if geometry[0] == geometry[-1]:
            instance.geometry = dumps(Polygon(geometry))
        else:
            instance.geometry = dumps(LineString(geometry))
    else:
        instance.geometry = dumps(Point(geometry))