django.contrib.gis.geos.MultiPolygon - python examples

Here are the examples of the python api django.contrib.gis.geos.MultiPolygon taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

20 Examples 7

3 View Complete Implementation : shpfile.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    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

3 View Complete Implementation : shapefile.py
Copyright MIT License
Author : azavea
def make_multipolygon(geom):
    """Wraps Polygons in MultiPolygons"""
    if isinstance(geom.geos, Polygon):
        return MultiPolygon(geom.geos)
    elif isinstance(geom.geos, MultiPolygon):
        return geom.geos
    else:
        raise ValueError('Feature is not a MultiPolygon or Polygon')

3 View Complete Implementation : test_views.py
Copyright MIT License
Author : azavea
    def setUp(self):
        boundary = Boundary.objects.create(label='fooOK', source_file='foo.zip',
                                           status=Boundary.StatusTypes.COMPLETE)
        coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
        self.poly = BoundaryPolygon.objects.create(data={},
                                                   geom=MultiPolygon(Polygon(LinearRing(coords))),
                                                   boundary=boundary)

3 View Complete Implementation : sacog_config_entities.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
    def regions(self, region_keys=None, clast_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_ensaties
                ))])
            },
        ]).matching_keys(key=region_keys).matching_scope(clast_scope=clast_scope)

3 View Complete Implementation : test_operations.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature("supports_3d_storage")
    @skipIf(spatialite, "Django currently doesn't support altering Spatialite geometry fields")
    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_clast_kwargs={'srid': 4326, 'dim': 3}
        )
        self.astertTrue(Neighborhood.objects.first().geom.hasz)
        # Rewind to 2 dimensions.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_clast_kwargs={'srid': 4326, 'dim': 2}
        )
        self.astertFalse(Neighborhood.objects.first().geom.hasz)

0 View Complete Implementation : shpfile.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    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

0 View Complete Implementation : mobile_survey.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def post(self, request, surveyid):
        data = JSONDeserializer().deserialize(request.body)
        if models.MobileSurveyModel.objects.filter(pk=data["id"]).exists() is False:
            mobile_survey_model = models.MobileSurveyModel(
                id=surveyid, name=data["name"], createdby=self.request.user, lasteditedby=self.request.user
            )
            mobile_survey_model.save()

        mobile_survey = MobileSurvey.objects.get(pk=data["id"])
        self.update_idensaties(data, mobile_survey, mobile_survey.users.all(), "users", User, models.MobileSurveyXUser)
        self.update_idensaties(data, mobile_survey, mobile_survey.groups.all(), "groups", Group, models.MobileSurveyXGroup)

        mobile_survey_card_ids = {str(c.cardid) for c in mobile_survey.cards.all()}
        form_card_ids = set(data["cards"])
        cards_to_remove = mobile_survey_card_ids - form_card_ids
        cards_to_add = form_card_ids - mobile_survey_card_ids
        cards_to_update = mobile_survey_card_ids & form_card_ids

        for card_id in cards_to_add:
            models.MobileSurveyXCard.objects.create(
                card=models.CardModel.objects.get(cardid=card_id), mobile_survey=mobile_survey, sortorder=data["cards"].index(card_id)
            )

        for card_id in cards_to_update:
            mobile_survey_card = models.MobileSurveyXCard.objects.filter(mobile_survey=mobile_survey).get(
                card=models.CardModel.objects.get(cardid=card_id)
            )
            mobile_survey_card.sortorder = data["cards"].index(card_id)
            mobile_survey_card.save()

        for card_id in cards_to_remove:
            models.MobileSurveyXCard.objects.filter(card=models.CardModel.objects.get(cardid=card_id), mobile_survey=mobile_survey).delete()

        # TODO Disabling the following section until we make emailing users optional
        # if mobile_survey.active != data['active']:
        # notify users in the mobile_survey that the state of the mobile_survey has changed
        # if data['active']:
        #     self.notify_mobile_survey_start(request, mobile_survey)
        # else:
        #     self.notify_mobile_survey_end(request, mobile_survey)
        mobile_survey.name = data["name"]
        mobile_survey.description = data["description"]
        mobile_survey.onlinebasemaps = data["onlinebasemaps"]
        if data["startdate"] != "":
            mobile_survey.startdate = data["startdate"]
        if data["enddate"] != "":
            mobile_survey.enddate = data["enddate"]
        mobile_survey.datadownloadconfig = data["datadownloadconfig"]
        mobile_survey.active = data["active"]
        mobile_survey.tilecache = data["tilecache"]
        polygons = []

        # try:
        #     data['bounds'].upper()
        #     data['bounds'] = json.loads(data['bounds'])
        # except AttributeError as e:
        #     print('bounds is not a string')

        if "features" in data["bounds"]:
            for feature in data["bounds"]["features"]:
                for coord in feature["geometry"]["coordinates"]:
                    polygons.append(Polygon(coord))

        elif len(polygons) == 0:
            try:
                if data["bounds"]["type"] == "MultiPolygon":
                    for poly in data["bounds"]["coordinates"]:
                        for coords in poly:
                            polygons.append(Polygon(coords))
            except AttributeError as e:
                print("bounds is not a geojson geometry object")

        mobile_survey.bounds = MultiPolygon(polygons)
        mobile_survey.lasteditedby = self.request.user

        try:
            with transaction.atomic():
                mobile_survey.save()
        except ConnectionRefusedError as e:
            error_satle = _("Unable to save collector project")
            error_message = _("Failed to connect to a CouchDB service")
            connection_error = JSONErrorResponse(error_satle, error_message)
            return connection_error
        except Exception as e:
            error_satle = _("Unable to save collector project")
            logger.exception(e)
            connection_error = JSONErrorResponse(error_satle, e)
            return connection_error

        return JSONResponse({"success": True, "mobile_survey": mobile_survey})

0 View Complete Implementation : test_filters.py
Copyright MIT License
Author : azavea
    def test_polygon_id_filter(self):
        """Test filtering by a polygon ID"""
        contains0_0 = BoundaryPolygon.objects.create(
            boundary=self.boundary,
            data={},
            geom=MultiPolygon(Polygon(((-1, -1), (1, -1), (1, 1), (-1, 1), (-1, -1))))
        )
        no_contains0_0 = BoundaryPolygon.objects.create(
            boundary=self.boundary,
            data={},
            geom=MultiPolygon(Polygon(((1, 1), (2, 1), (2, 2), (1, 2), (1, 1))))
        )
        # Test a geometry that contains the records
        contained_record_count = len([self.id_record_1, self.id_record_2,
                                      self.item_record_1, self.item_record_2])
        queryset = self.filter_backend.filter_polygon_id(self.queryset, 'geom', contains0_0.pk)
        self.astertEqual(queryset.count(), contained_record_count)

        # Test a geometry that does not contain any of the records
        queryset = self.filter_backend.filter_polygon_id(self.queryset, 'geom', no_contains0_0.pk)
        self.astertEqual(queryset.count(), 0)

        # Test leaving out an ID (this should include nongeospatial records, too)
        full_record_count = len([self.id_record_1, self.id_record_2,
                                 self.item_record_1, self.item_record_2,
                                 self.nongeospatial_record])
        queryset = self.filter_backend.filter_polygon_id(self.queryset, 'geom', None)
        self.astertEqual(queryset.count(), full_record_count)

0 View Complete Implementation : test_serializer_fields_bbox.py
Copyright MIT License
Author : azavea
    def setUp(self):
        self.bbox_field = GeomBBoxField()
        self.poly = MultiPolygon(Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))))

0 View Complete Implementation : test_views.py
Copyright MIT License
Author : azavea
    @clastmethod
    def setUpClast(cls):
        super(MultiPolygonRecordViewTestCase, cls).setUpClast()

        # Create dummy data for a MultiPolygon Recordtype.
        cls.coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
        cls.multipolygon_record_type = RecordType.objects.create(label='Multipolygon',
                                                                 plural_label='Multipolygons',
                                                                 geometry_type='multipolygon',
                                                                 temporal=True)
        cls.multipolygon_schema = RecordSchema.objects.create(record_type=cls.multipolygon_record_type,
                                                              version=1,
                                                              schema={})
        cls.multipolygon_record = Record.objects.create(schema=cls.multipolygon_schema,
                                                        data='{}',
                                                        occurred_from=timezone.now(),
                                                        occurred_to=timezone.now(),
                                                        geom=MultiPolygon(Polygon(LinearRing(cls.coords))))

        # The base endpoint for listing records.
        cls.record_endpt = reverse('record-list')