Python django.contrib.gis.geos.GEOSGeometry() Examples
The following are 30
code examples of django.contrib.gis.geos.GEOSGeometry().
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: search.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def _buffer(geojson, width=0, unit="ft"): geojson = JSONSerializer().serialize(geojson) geom = GEOSGeometry(geojson, srid=4326) try: width = float(width) except Exception: width = 0 if width > 0: if unit == "ft": width = width / 3.28084 geom.transform(settings.ANALYSIS_COORDINATE_SYSTEM_SRID) geom = geom.buffer(width) geom.transform(4326) return geom
Example #2
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_collect(self): """ Testing the `Collect` aggregate. """ # Reference query: # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id") # WHERE "relatedapp_city"."state" = 'TX'; ref_geom = GEOSGeometry( 'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,' '-95.363151 29.763374,-96.801611 32.782057)' ) coll = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect'] # Even though Dallas and Ft. Worth share same point, Collect doesn't # consolidate -- that's why 4 points in MultiPoint. self.assertEqual(4, len(coll)) self.assertTrue(ref_geom.equals(coll))
Example #3
Source File: tests.py From gazetteer with MIT License | 6 votes |
def test_change_component(self): state1 = Place.objects.get("state1") #west (our composite place will not be comprised with this one) state2 = Place.objects.get("state2") #south_east state3 = Place.objects.get("state3") #north_east comp_place1 = Place.objects.get(self.comp_place_id_1) comp_place1.add_relation(state2, "comprised_by", {"comment":"comp place comprised by state2"}) comp_place1.add_relation(state3, "comprised_by", {"comment":"comp place comprised by state3"}) comp_copy = comp_place1.copy() composite_area = GEOSGeometry(json.dumps(comp_copy.geometry)).area state3_area = GEOSGeometry(json.dumps(state3.geometry)).area state3.geometry = {"type":"Polygon", "coordinates":[[[-103.0892050625, 45.75121434375], [-94.3880331875, 46.01488621875], [-94.3880331875, 37.92894871875], [-103.0892050625, 37.92894871875], [-103.0892050625, 45.75121434375]]]} state3.save() state3_smaller_area = GEOSGeometry(json.dumps(state3.geometry)).area self.assertLess(state3_smaller_area, state3_area) comp_copy2 = comp_place1.copy() composite_smaller_area = GEOSGeometry(json.dumps(comp_copy2.geometry)).area self.assertLess(composite_smaller_area, composite_area) #if the component has its relation removed, it should change the composite place automatically
Example #4
Source File: test_geoforms.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) tol = 0.0000001 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) # The cleaned geometry is transformed to 32140 (the widget map_srid is 3857). cleaned_geom = fld.clean('SRID=3857;POINT (-10615777.40976205 3473169.895707852)') self.assertEqual(cleaned_geom.srid, 32140) self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
Example #5
Source File: test_geoforms.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): with self.subTest(wkt=wkt): # to_python() uses the SRID of OpenLayersWidget if the # converted value doesn't have an SRID. self.assertEqual(GEOSGeometry(wkt, srid=fld.widget.map_srid), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)', srid=pnt_fld.widget.map_srid), pnt_fld.clean('POINT(5 23)')) # a WKT for any other geom_type will be properly transformed by `to_python` self.assertEqual( GEOSGeometry('LINESTRING(0 0, 1 1)', srid=pnt_fld.widget.map_srid), pnt_fld.to_python('LINESTRING(0 0, 1 1)') ) # but rejected by `clean` with self.assertRaises(forms.ValidationError): pnt_fld.clean('LINESTRING(0 0, 1 1)')
Example #6
Source File: alerts.py From BikeMaps with MIT License | 6 votes |
def postAlertPolygon(request): geofenceForm = GeofenceForm(request.POST) geofenceForm.data = geofenceForm.data.copy() # Create valid attributes for user and geom fields try: geofenceForm.data['user'] = request.user.id geofenceForm.data['geom'] = GEOSGeometry(geofenceForm.data['geom']) except(ValueError): messages.error(request, '<strong>' + _('Error') + '</strong><br>' + _('Invalid geometry data.')) if geofenceForm.is_valid(): # Save new model object, send success message to the user polygon = geofenceForm.save() # messages.success(request, _('You will now receive alerts for the area traced.')) return JsonResponse({ 'success': True, 'polygon': GeoJSONSerializer().serialize([polygon,]) }) else: return JsonResponse({'success': False})
Example #7
Source File: place.py From gazetteer with MIT License | 6 votes |
def assign_admin(self): if self.is_composite or self.timeframe or not self.centroid: return False centroid_geom = str({"type":"Point", "coordinates": self.centroid}) place_geom = GEOSGeometry(centroid_geom) temp_admin = list(self.admin) for existing_admin in self.admin: if existing_admin.get("id"): temp_admin.remove(existing_admin) self.admin = list(temp_admin) results = AdminBoundary.objects.filter(queryable_geom__contains=place_geom) if results: for boundary in results: self.add_admin(boundary.to_place_json()) return self.admin #unions a places geometry with another geometry
Example #8
Source File: place.py From gazetteer with MIT License | 6 votes |
def union_geometry(self, target_geometry): #the target could have no geometry if not target_geometry: return True #composite place could have no geometry (especially at the beginning) if not self.geometry: self.geometry = target_geometry return True place_geom = GEOSGeometry(json.dumps(self.geometry)) target_geom = GEOSGeometry(json.dumps(target_geometry)) union = place_geom.union(target_geom) self.geometry = json.loads(union.json) return True #method for composite places. #Goes through the component places does a union on them and assigns the geometry to the result #Works with polygons and multipolygons or points and multipoints.
Example #9
Source File: zoom.py From openhgsenti with Apache License 2.0 | 6 votes |
def get_zoom(self, geom): "Returns the optimal Zoom level for the given geometry." # Checking the input type. if not isinstance(geom, GEOSGeometry) or geom.srid != 4326: raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') # Getting the envelope for the geometry, and its associated width, height # and centroid. env = geom.envelope env_w, env_h = self.get_width_height(env.extent) center = env.centroid for z in range(self._nzoom): # Getting the tile at the zoom level. tile_w, tile_h = self.get_width_height(self.tile(center, z).extent) # When we span more than one tile, this is an approximately good # zoom level. if (env_w > tile_w) or (env_h > tile_h): if z == 0: raise GoogleMapException('Geometry width and height should not exceed that of the Earth.') return z - 1 # Otherwise, we've zoomed in to the max. return self._nzoom - 1
Example #10
Source File: fields.py From openhgsenti with Apache License 2.0 | 6 votes |
def to_python(self, value): """ Transforms the value to a Geometry object. """ if value in self.empty_values: return None if not isinstance(value, GEOSGeometry): try: value = GEOSGeometry(value) except (GEOSException, ValueError, TypeError): raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom') # Try to set the srid if not value.srid: try: value.srid = self.widget.map_srid except AttributeError: if self.srid: value.srid = self.srid return value
Example #11
Source File: geo_fields.py From drf-extra-fields with Apache License 2.0 | 6 votes |
def to_representation(self, value): """ Transform POINT object to json. """ if value is None: return value if isinstance(value, GEOSGeometry): value = { "latitude": value.y, "longitude": value.x } if self.str_points: value['longitude'] = smart_str(value.pop('longitude')) value['latitude'] = smart_str(value.pop('latitude')) return value
Example #12
Source File: map_filter.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def _buffer(geojson, width=0, unit="ft"): geojson = JSONSerializer().serialize(geojson) geom = GEOSGeometry(geojson, srid=4326) try: width = float(width) except Exception: width = 0 if width > 0: if unit == "ft": width = width / 3.28084 geom.transform(settings.ANALYSIS_COORDINATE_SYSTEM_SRID) geom = geom.buffer(width) geom.transform(4326) return geom
Example #13
Source File: geo_fields.py From drf-extra-fields with Apache License 2.0 | 6 votes |
def to_internal_value(self, value): """ Parse json data and return a point object """ if value in EMPTY_VALUES and not self.required: return None if isinstance(value, string_types): try: value = value.replace("'", '"') value = json.loads(value) except ValueError: self.fail('invalid') if value and isinstance(value, dict): try: latitude = value.get("latitude") longitude = value.get("longitude") return GEOSGeometry('POINT(%(longitude)s %(latitude)s)' % { "longitude": longitude, "latitude": latitude} ) except (GEOSException, ValueError): self.fail('invalid') self.fail('invalid')
Example #14
Source File: datatypes.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def transform_value_for_tile(self, value, **kwargs): if "format" in kwargs and kwargs["format"] == "esrijson": arches_geojson = GeoUtils().arcgisjson_to_geojson(value) else: arches_geojson = {} arches_geojson["type"] = "FeatureCollection" arches_geojson["features"] = [] geometry = GEOSGeometry(value, srid=4326) if geometry.geom_type == "GeometryCollection": for geom in geometry: arches_json_geometry = {} arches_json_geometry["geometry"] = JSONDeserializer().deserialize(GEOSGeometry(geom, srid=4326).json) arches_json_geometry["type"] = "Feature" arches_json_geometry["id"] = str(uuid.uuid4()) arches_json_geometry["properties"] = {} arches_geojson["features"].append(arches_json_geometry) else: arches_json_geometry = {} arches_json_geometry["geometry"] = JSONDeserializer().deserialize(geometry.json) arches_json_geometry["type"] = "Feature" arches_json_geometry["id"] = str(uuid.uuid4()) arches_json_geometry["properties"] = {} arches_geojson["features"].append(arches_json_geometry) return arches_geojson
Example #15
Source File: datatypes.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def get_bounds_from_value(self, node_data): bounds = None for feature in node_data["features"]: geom_collection = GEOSGeometry(JSONSerializer().serialize(feature["geometry"])) if bounds is None: bounds = geom_collection.extent else: minx, miny, maxx, maxy = bounds if geom_collection.extent[0] < minx: minx = geom_collection.extent[0] if geom_collection.extent[1] < miny: miny = geom_collection.extent[1] if geom_collection.extent[2] > maxx: maxx = geom_collection.extent[2] if geom_collection.extent[3] > maxy: maxy = geom_collection.extent[3] bounds = (minx, miny, maxx, maxy) return bounds
Example #16
Source File: test_user_management.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
def globalSetup(): # Bootstrap GlobalConfig._no_post_save_publishing = True GlobalConfig.objects.update_or_create( key=Keys.GLOBAL_CONFIG_KEY, defaults=dict(bounds=GEOSGeometry('MULTIPOLYGON EMPTY')) ) GlobalConfig._no_post_save_publishing = False update_or_create_group('superadmin') update_or_create_user(username='superadmin', password='test_superadmin_user@uf', email='test_superadmin_user@calthorpeanalytics.com', api_key=None, groups=['superadmin'], is_super_user=True) return GlobalConfig.objects.update_or_create( key='global', defaults=dict( name='Global Config', scope='global', bounds='MULTIPOLYGON (((-20037508.3399999998509884 -20037508.3399999998509884, -20037508.3399999998509884 20037508.3399999998509884, \ 20037508.3399999998509884 20037508.3399999998509884, 20037508.3399999998509884 -20037508.3399999998509884, \ -20037508.3399999998509884 -20037508.3399999998509884)))' ) )[0]
Example #17
Source File: fields.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def to_python(self, value): """ Transforms the value to a Geometry object. """ if value in self.empty_values: return None if not isinstance(value, GEOSGeometry): try: value = GEOSGeometry(value) except (GEOSException, ValueError, TypeError): raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom') # Try to set the srid if not value.srid: try: value.srid = self.widget.map_srid except AttributeError: if self.srid: value.srid = self.srid return value
Example #18
Source File: geo_json_processor.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
def instantiate_sub_class(self, feature_class, feature): """ Instantiates an instance of the dynamic subclass of GeoJsonFeature based on the given feature. :param feature: A feature parsed django-geojson. The feature is actually reserialized to json in order to construct a GEOSGeometry instance. :return: An instance of the GeoJsonFeature subclass, which contains the geometry, properties of the feature, and perhaps the crs """ # TODO, crs should be read from the geojson when present. # This crs isn't actually picked up by the GEOSGeometry constructor srid = settings.SRID_PREFIX.format(settings.DEFAULT_SRID) crs = { "type": "name", "properties": { "name": srid } } # Ironically, we have to rejsonify the data so that GEOSGeometry can parse the feature as json json = jsonify({'type':feature.geometry.type, 'coordinates':feature.geometry.coordinates, 'crs':crs}) geometry = GEOSGeometry(json) field_dict = map_to_dict(lambda field: [field.name, feature.properties[field.name]], filter(lambda field: feature.properties.get(field.name, None), feature_class._meta.fields)) return feature_class(wkb_geometry=geometry, **field_dict)
Example #19
Source File: tests.py From BikeMaps with MIT License | 6 votes |
def setUp(self): pnt_geom = GEOSGeometry('POINT(-123.5 48.5)') now_time = datetime.now() # Create hazards that fall into different categories # TODO: Auto implement hazard_category or make a required field self._infrastructure = Hazard.objects.create(geom=pnt_geom, date=now_time, i_type="Pothole", hazard_category="infrastructure") self._environmental = Hazard.objects.create(geom=pnt_geom, date=now_time, i_type="Wet leaves", hazard_category="environmental") self._human_behaviour = Hazard.objects.create(geom=pnt_geom, date=now_time, i_type="Driver behaviour", hazard_category="human behaviour") self._environmental.save()
Example #20
Source File: zoom.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_zoom(self, geom): "Returns the optimal Zoom level for the given geometry." # Checking the input type. if not isinstance(geom, GEOSGeometry) or geom.srid != 4326: raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') # Getting the envelope for the geometry, and its associated width, height # and centroid. env = geom.envelope env_w, env_h = self.get_width_height(env.extent) center = env.centroid for z in range(self._nzoom): # Getting the tile at the zoom level. tile_w, tile_h = self.get_width_height(self.tile(center, z).extent) # When we span more than one tile, this is an approximately good # zoom level. if (env_w > tile_w) or (env_h > tile_h): if z == 0: raise GoogleMapException('Geometry width and height should not exceed that of the Earth.') return z - 1 # Otherwise, we've zoomed in to the max. return self._nzoom - 1
Example #21
Source File: tests.py From BikeMaps with MIT License | 6 votes |
def setUp(self): pnt_geom = GEOSGeometry('POINT(-123.5 48.5)') now_time = datetime.now() # Collision self._collision = Incident.objects.create(geom=pnt_geom, date=now_time, i_type="Collision with moving object or vehicle", incident_with="Vehicle, side", injury="Injury, no treatment") # Nearmiss self._nearmiss = Incident.objects.create(geom=pnt_geom, date=now_time, i_type="Near collision with stationary object or vehicle", incident_with="Vehicle, side", injury="Injury, no treatment") # Fall self._fall = Incident.objects.create(geom=pnt_geom, date=now_time, i_type="Fall", incident_with="Vehicle, side", injury="Injury, no treatment")
Example #22
Source File: fields.py From bioforum with MIT License | 6 votes |
def to_python(self, value): """Transform the value to a Geometry object.""" if value in self.empty_values: return None if not isinstance(value, GEOSGeometry): try: value = GEOSGeometry(value) except (GEOSException, ValueError, TypeError): raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom') # Try to set the srid if not value.srid: try: value.srid = self.widget.map_srid except AttributeError: if self.srid: value.srid = self.srid return value
Example #23
Source File: __init__.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def add_huge_project(self, max_num_records=4000): project = models.Project.objects.get(slug='london-2') content_type = ContentType.objects.get( app_label='spatial', model='spatialunit') attr_type = AttributeType.objects.get(name="text") sch = Schema.objects.create( content_type=content_type, selectors=(project.organization.pk, project.pk)) Attribute.objects.create( schema=sch, name='name', long_name='Name', required=False, index=1, attr_type=attr_type ) spatial_units = [] choices = [c[0] for c in TYPE_CHOICES] with open(os.path.join(os.path.dirname(__file__), "londondata.txt"), "r") as ins: for geometry in ins: if not geometry.rstrip() or geometry.startswith('#'): continue num_records = len(spatial_units) if not num_records < max_num_records: break name = 'Spatial Unit #{}'.format(num_records) type = random.choice(choices) spatial_units.append({ 'geometry': GEOSGeometry(geometry), 'type': type, 'project': project, 'attributes': {'name': name} }) SpatialUnitFactory.create_from_kwargs(spatial_units)
Example #24
Source File: test_models.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def test_empty_geometry(self): # Temp workaround where 'POLYGON EMPTY' is cast to None. Should # be removed when Django is 1.11+ or libgeos is 3.6.1+ spatial_unit = SpatialUnitFactory.create( geometry=GEOSGeometry('POLYGON EMPTY')) assert spatial_unit.geometry is None
Example #25
Source File: test_forms.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_upload_field(self): geom = geos.GEOSGeometry(json.dumps(_geom)) fp = SimpleUploadedFile('up.json', geom.geojson.encode('ascii')) form = forms.RasterQueryForm({}, files={'upload': fp}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['g'], geom.ogr) self.assertEqual(form.cleaned_data['g'].srs.srid, 4326)
Example #26
Source File: test_forms.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_from_request(self): request = factory.post('/', json.dumps({'g': _geom}), content_type='application/json') view = APIView() request = view.initialize_request(request) view.initial(request) form = forms.RasterQueryForm.from_request(request) self.assertTrue(form.is_valid()) geom = geos.GEOSGeometry(json.dumps(_geom)) self.assertEqual(form.cleaned_data['g'], geom.ogr)
Example #27
Source File: model_helper.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def create_spatial_unit(self, data, project, party=None, duplicate=None): location_resources = [] location_objects = [] try: location_group = self._format_repeat(data, ['location']) for group in location_group: geom = self._format_geometry(group) attrs = dict( project=project, type=group['location_type'], attributes=self._get_attributes(group, 'location') ) if duplicate: geom_type = GEOSGeometry(geom).geom_type GeometryField = getattr(geo_models, geom_type + 'Field') location = duplicate.spatial_units.annotate( geom=Cast('geometry', GeometryField()) ).get(geom=geom, **attrs) else: location = SpatialUnit.objects.create(geometry=geom, **attrs) location_resources.append( self._get_resource_names(group, location, 'location') ) location_objects.append(location) except Exception as e: raise InvalidXMLSubmission(_( 'Location error: {}'.format(e))) return location_objects, location_resources
Example #28
Source File: test_serializers.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_serialize_queryset_simplify(self): fn = query.Simplify(functions.Transform('geom', 4269), 1.01) qs = Location.objects.all() for obj in qs: obj.geom = obj.geom.buffer(1.5) obj.save() qs = qs.annotate(simplify=fn) obj = qs[0] serializer = SimplifyLocationSerializer(obj) g = geos.GEOSGeometry(json.dumps(serializer.data['geometry']), srid=obj.simplify.srid) self.assertEqual(g, obj.simplify) self.assertEqual(obj.simplify.srid, 4269) self.assertEqual(serializer.data['crs']['properties']['name'][-4:], '4269')
Example #29
Source File: views.py From tracker_project with MIT License | 5 votes |
def form_valid(self, form): form.instance.location = GEOSGeometry(form.cleaned_data['location_geojson']) return super(IncidentUpdateView, self).form_valid(form)
Example #30
Source File: test_generics.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_api_response(self): response = self.client.get(self.url, HTTP_ACCEPT='text/html') wkt = re.search('POLYGON[^&]+', response.content.decode('utf-8')).group() g = geos.GEOSGeometry(wkt) self.assertEqual(g, self.qs[0].geom.wkt)