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

The following are 14 code examples of django.contrib.gis.geos.MultiPolygon(). 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: shpfile.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def convert_geom(self, geos_geom):
        """Coverts GEOS geometries to shapefile geometries"""
        if geos_geom.geom_type == "Point":
            multi_geom = MultiPoint(geos_geom)
            shp_geom = [[c for c in multi_geom.coords]]
        if geos_geom.geom_type == "LineString":
            multi_geom = MultiLineString(geos_geom)
            shp_geom = [c for c in multi_geom.coords]
        if geos_geom.geom_type == "Polygon":
            multi_geom = MultiPolygon(geos_geom)
            shp_geom = [c[0] for c in multi_geom.coords]
        if geos_geom.geom_type == "MultiPoint":
            shp_geom = [c for c in geos_geom.coords]
        if geos_geom.geom_type == "MultiLineString":
            shp_geom = [c for c in geos_geom.coords]
        if geos_geom.geom_type == "MultiPolygon":
            shp_geom = [c[0] for c in geos_geom.coords]

        return shp_geom 
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: combined_config_entity.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def save(self, force_insert=False, force_update=False, using=None):
        """
            Overrides the default save to merge the self.config_entities properties after doing an initial save
        :param force_insert:
        :param force_update:
        :param using:
        :return:
        """

        # First save to create a pk
        super(CombinedConfigEntity, self).save(force_insert, force_update, using)
        # Add unique instances to each collection from the config_entities. References to the parent_config_entity's
        # instances will automatically be adopted first.
        for method in ConfigEntity.INHERITABLE_COLLECTIONS:
            # get the add_method or add_method_through method name
            getattr(self, '_add_{0}'.format(method))(
                *unique(
                    flat_map(
                        lambda config_entity: getattr(config_entity, 'computed_{0}'.format(method))(),
                        self.config_entities),
                    lambda instance: instance.pk))

        # Combine the bounds of the config_entities to make this instance's bounds
        self.bounds = MultiPolygon(map(lambda config_entity: config_entity.bounds.cascaded_union, self.config_entities)) 
Example #4
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 #5
Source File: scag_dm_config_entities.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def regions(self, region_keys=None, class_scope=None):
        return FixtureList([
            dict(
                key='scag',
                name='The SCAG Region',
                description='Jurisdictions of the SCAG Region',
                media=[
                    MediumFixture(key=ConfigEntityMediumKey.Fab.ricate('scag_logo'), name='SCAG Logo',
                                    url='/static/client/{0}/logos/scag_dm.png'.format(settings.CLIENT))
                ],
                #defaulting to an Irvine view for the moment
                bounds=MultiPolygon([Polygon((
                    (-117.869537353516, 33.5993881225586),
                    (-117.869537353516, 33.7736549377441),
                    (-117.678024291992, 33.7736549377441),
                    (-117.678024291992, 33.5993881225586),
                    (-117.869537353516, 33.5993881225586),
                ))])
            )
        ]).matching_keys(key=region_keys).matching_scope(class_scope=class_scope) 
Example #6
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 #7
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 #8
Source File: place.py    From gazetteer with MIT License 5 votes vote down vote up
def calc_composite_geometry(self):
        geometries = []

        if not self.is_composite:
            return False

        for relation in self.relationships:
            if relation["type"] == "comprised_by":
                relation_geometry = Place.objects.get(relation["id"]).geometry
                if relation_geometry:
                    geos_geom = GEOSGeometry(json.dumps(relation_geometry))
                    if geos_geom.geom_type == "MultiPolygon" or geos_geom.geom_type == "MutliPoint":
                        for indiv_geom in geos_geom:
                            geometries.append(indiv_geom)
                    elif geos_geom.geom_type == "Polygon" or geos_geom.geom_type == "Point":
                        geometries.append(geos_geom)
                    else:
                        pass
                        
        if not geometries:
            return False
            
        if geometries[0].geom_type == "Polygon":
            union = MultiPolygon(geometries).cascaded_union
        elif geometries[0].geom_type == "Point":
            union = MultiPoint(geometries)
            
        self.geometry = json.loads(union.json)
        self.centroid = union.centroid.coords
        
        return True 
Example #9
Source File: shpfile.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_feature_geoms(self, resource, geom_field):
        """
        Reduces an instances geometries from a geometry collection, that potentially has any number of points, lines
        and polygons, down to a list containing a MultiPoint and/or a MultiLine, and/or a MultiPolygon object.
        """
        result = []
        sorted_geoms = {"points": [], "lines": [], "polys": []}
        for geom in resource[geom_field]:
            if geom.geom_typeid == 0:
                sorted_geoms["points"].append(geom)
            if geom.geom_typeid == 1:
                sorted_geoms["lines"].append(geom)
            if geom.geom_typeid == 3:
                sorted_geoms["polys"].append(geom)
            if geom.geom_typeid == 4:
                for feat in geom:
                    sorted_geoms["points"].append(feat)
            if geom.geom_typeid == 5:
                for feat in geom:
                    sorted_geoms["lines"].append(feat)
            if geom.geom_typeid == 6:
                for feat in geom:
                    sorted_geoms["polys"].append(feat)

        if len(sorted_geoms["points"]) > 0:
            result.append(MultiPoint(sorted_geoms["points"]))
        if len(sorted_geoms["lines"]) > 0:
            result.append(MultiLineString(sorted_geoms["lines"]))
        if len(sorted_geoms["polys"]) > 0:
            result.append(MultiPolygon(sorted_geoms["polys"]))

        return result 
Example #10
Source File: conftest.py    From linkedevents with MIT License 5 votes vote down vote up
def administrative_division(administrative_division_type, municipality):
    division = AdministrativeDivision.objects.create(
        name_en='test division',
        type=administrative_division_type,
        ocd_id='ocd-division/test:1',
        municipality=municipality,
    )
    coords = ((0, 0), (0, 200), (200, 200), (200, 0), (0, 0))
    AdministrativeDivisionGeometry.objects.create(division=division, boundary=MultiPolygon([Polygon(coords)]))
    return division 
Example #11
Source File: conftest.py    From linkedevents with MIT License 5 votes vote down vote up
def administrative_division2(administrative_division_type):
    division = AdministrativeDivision.objects.create(
        name_en='test division 2',
        type=administrative_division_type,
        ocd_id='ocd-division/test:2'
    )
    coords = ((100, 100), (100, 300), (300, 300), (300, 100), (100, 100))
    AdministrativeDivisionGeometry.objects.create(division=division, boundary=MultiPolygon([Polygon(coords)]))
    return division 
Example #12
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 #13
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 #14
Source File: project.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def recalculate_bounds(self):

        primary_geography_feature_classes = [self.db_entity_feature_class(db_entity.key)
                                     for db_entity in self.owned_db_entities() if
                                     get_property_path(db_entity, 'feature_class_configuration.primary_geography')]

        use_for_bounds_feature_classes = [self.db_entity_feature_class(db_entity.key)
                                     for db_entity in self.owned_db_entities() if
                                     get_property_path(db_entity, 'feature_class_configuration.use_for_bounds')]

        authority_feature_classes = use_for_bounds_feature_classes if len(use_for_bounds_feature_classes) > 0 \
            else primary_geography_feature_classes

        extents = []
        for authority_feature_class in authority_feature_classes:
            all_features = authority_feature_class.objects.all()
            if len(all_features) > 0:
                bounds = all_features.extent_polygon()
                extents.append(bounds)
                self.bounds = MultiPolygon(extents)
                # Disable publishers for this simple update
                self._no_post_save_publishing = True
                self.save()
                self._no_post_save_publishing = False
            else:
                pass