def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context.update(self.get_queryset().aggregate( count=Count('spatial_id', distinct=True), coordinates=ArrayAgg(AsGeoJSON(Centroid('footprint'))), instrumentation_count=Count( 'instrumentation', distinct=True, filter=Q(instrumentation__isnull=False), ), acquisition_date__min=Min( 'acquisition_date', filter=Q(acquisition_date__isnull=False)), acquisition_date__max=Max( 'acquisition_date', filter=Q(acquisition_date__isnull=False)), extents=Extent('outline'), )) context['coordinates'] = '[' + ','.join(context['coordinates']) + ']' extents = context['extents'] or [None] * 4 context['extents'] = json.dumps({ 'xmin': extents[0], 'ymin': extents[1], 'xmax': extents[2], 'ymax': extents[3], }) return context
def test_geojson(self): """ Test GeoJSON() function with Z values. """ self._load_city_data() h = City3D.objects.annotate(geojson=AsGeoJSON('point', precision=6)).get(name='Houston') # GeoJSON should be 3D # `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';` ref_json_regex = re.compile(r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$') self.assertTrue(ref_json_regex.match(h.geojson))
def handle(self, *args, **options): states = State.objects.all().annotate( centroid=AsGeoJSON(Centroid('geometry')), ) for state in states: center_data = json.loads(state.centroid) lng = center_data['coordinates'][0] lat = center_data['coordinates'][1] state.center_lng = lng state.center_lat = lat state.save()
def select_aoj_request(request): aoj_code = json.loads(request.GET["code"]) tr_c2 = os.path.abspath( os.path.join(os.path.dirname(transformer_model.__file__), 'data', 'DS_Transformer_C2_Pro.shp')) aoj = Aoj_C2.objects.all().filter(code=aoj_code) aoj_poly = aoj[0].geom print(type(aoj_poly)) tr = Transformer_C2.objects.all().filter(geom__within=aoj_poly) print(len(tr)) qs = Aoj_C2.objects.all().filter(code=aoj_code).annotate( cent=AsGeoJSON(Centroid('geom'))) for i in qs.values(): print(json.loads(i.get("cent")).get("coordinates")) centroid_aoj = json.loads(i.get("cent")).get("coordinates") res = serialize( 'geojson', Aoj_C2.objects.all().filter(code=aoj_code), fields=('geom', ), ) result = [] result_dict = {} for i in tr: # point_tr.append(i.geom.geojson) # pea_no.append(i.facilityid) # print(type(i.geom.json)) json_obj = json.loads(i.geom.json) result_dict.update({ "peano": i.facilityid, "ratekva": i.ratekva, "gistag": i.tag, "feederID": i.feederid, "phase": i.phasedesig, "name": i.name, "flag": i.flag, "impact": i.impact, "baseload": i.loadProfile_base, "evload": i.loadProfile_ev, "coordinate": json_obj["coordinates"] }) result.append(result_dict) result_dict = {} print(result) return JsonResponse({"data": res, "coordinate_cent" : centroid_aoj, \ "point": json.dumps(result)})
def select_aoj_request(request): # function for select by location and send data to map aoj_code = json.loads(request.GET["code"]) # get AOJ code from html aoj = Aoj_C2.objects.all().filter(code=aoj_code) # AOJ queryset from Models aoj_poly = aoj[0].geom # aoj_poly is Geometry Dataset tr = Transformer_C2.objects.all().filter(geom__within = aoj_poly) # Transformer in AOJ Polygon # built AOJ GeoJSON object and add centroid in fields cent. qs = Aoj_C2.objects.all().filter(code=aoj_code).annotate(cent=AsGeoJSON(Centroid('geom'))) for i in qs.values(): print(json.loads(i.get("cent")).get("coordinates")) centroid_aoj = json.loads(i.get("cent")).get("coordinates") res = serialize( # pack GeoJSON in res variable. 'geojson', Aoj_C2.objects.all().filter(code=aoj_code), fields=('geom', ), ) tr_geojson = serialize( 'geojson', Transformer_C2.objects.all().filter(geom__within = aoj_poly), fields=('geom', ), ) result = [] result_dict = {} for i in tr : json_obj = json.loads(i.geom.json) # Edit JSON Schema if you want addition more fields. result_dict.update({"peano": i.facilityid, "ratekva": i.ratekva, "gistag" : i.tag, "feederID": i.feederid, "phase" : i.phasedesig, "name" : i.name, "flag" : i.flag, "impact" : i.impact, "baseload" : i.loadProfile_base, "numberOfCustomer" : i.numberOfCustomer, "evload" : i.loadProfile_ev, "coordinate": json_obj["coordinates"]}) result.append(result_dict) result_dict = {} # data = json.loads(tr_geojson) # with open("./transformer_geojson.json", 'w') as f: # json.dump(data, f) return JsonResponse({ "data": res, \ "coordinate_cent" : centroid_aoj, \ "point": json.dumps(result) })
def checkgeometries(): """ Check to see if any geometries corrupted """ allgeometries = Geometry.objects.all().annotate( json=AsGeoJSON('geometry')).values('name', 'code', 'zoom', 'type', 'json').order_by( 'code', 'type', 'zoom') for geometry in allgeometries: print("Checking geometry", geometry['code'], geometry['type'], geometry['zoom']) json_data = json.dumps(list(geometry), cls=DjangoJSONEncoder)
def get_country_centroid_as_geojson(name): """ Gets a country centroid as GeoJSON hint: nested geofunction calls """ if (name[0].islower()): name = get_capitalized_country_name(name) try: country = Country.objects.annotate( json=AsGeoJSON(Centroid('mpoly'))).get(name=name).json return (country) except Country.DoesNotExist as error: raise Country.DoesNotExist(error)
def get_country_border_as_geojson(name): """ Gets a country name and returns its corresponding GeoJSON object """ if (name[0].islower()): name = get_capitalized_country_name(name) try: country = Country.objects.annotate(json=AsGeoJSON('mpoly')).get( name=name).json return (country) except Country.DoesNotExist as error: raise Country.DoesNotExist(error)
def decorate_queryset(self, feature_type: FeatureType, queryset, output_crs, **params): """Update the queryset to let the database render the GML output. This is far more efficient then GeoDjango's logic, which performs a C-API call for every single coordinate of a geometry. """ queryset = super().decorate_queryset(feature_type, queryset, output_crs, **params) # If desired, the entire FeatureCollection could be rendered # in PostgreSQL as well: https://postgis.net/docs/ST_AsGeoJSON.html match = feature_type.resolve_element(feature_type.geometry_field_name) return queryset.defer(feature_type.geometry_field_name).annotate( _as_db_geojson=AsGeoJSON(get_db_geometry_target(match, output_crs), precision=16))
def Geometries(request): """ Get all geometries within boundary box for particular zoom level """ data = json.loads(request.body) geometrytype, zoom, xmin, ymin, xmax, ymax = data['geometrytype'], data[ 'zoom'], data['xmin'], data['ymin'], data['xmax'], data['ymax'] type = geometrytypecode[int(geometrytype) - 1] # print(type, zoom, xmin, ymin, xmax, ymax) bbox = (xmin, ymin, xmax, ymax) geometry = Polygon.from_bbox(bbox) allfeatures = Geometry.objects.filter( zoom=zoom, type=type, geometry__bboverlaps=geometry).annotate( json=AsGeoJSON('geometry')).values('name', 'code', 'type', 'json') json_data = json.dumps(list(allfeatures), cls=DjangoJSONEncoder) return HttpResponse(json_data, content_type="text/json")
def space_centroid(request, space_id): space_qs = BuildingFloorSpace.objects.filter(pk=space_id) if space_qs: att = space_qs.values()[0] if att['multi_poly']: att['multi_poly'] = None centroid_res = BuildingFloorSpace.objects.annotate( json=AsGeoJSON(Centroid('multi_poly'))).get(pk=space_id).json res = Feature(geometry=json.loads(centroid_res), properties=att) return Response(res) else: return Response({ 'error': 'Sorry we did not find any record in our database matching your id = ' + str(space_id) })
def index(request): isim = "django" __states = State.objects.annotate(json=AsGeoJSON('geometry')).get(name="test").json return render(request, "index.html", locals())
def get_queryset(self): return super().get_queryset().annotate(_area=Area('geometry'), _geoJSON=AsGeoJSON('geometry'))
def getfeature(request, service, wfs_version): context = {} propertyname = None featureversion = None maxfeatures = None typename = None featureid = None filtr = None bbox = None bbox_has_crs = False outputFormat = None resolution = None # A fallback value, if no features can be found crs = WGS84_CRS for key, value in request.GET.items(): low_key = key.lower() low_value = value.lower() if low_key == "propertyname": propertyname = low_value elif low_key == "featureversion": featureversion = low_value elif low_key == "maxfeatures": try: maxfeatures = int(low_value) except: return wfs_exception(request, "InvalidParameterValue", "maxfeatures", value) else: if maxfeatures < 1: return wfs_exception(request, "InvalidParameterValue", "maxfeatures", value) elif low_key == "typename": typename = low_value elif low_key == "featureid": featureid = low_value elif low_key == "filter": filtr = low_value elif low_key == "resolution": try: resolution = float(low_value) except: return wfs_exception(request, "InvalidParameterValue", "resolution", value) elif low_key == "bbox": # # See the following URL for all the gory details on the passed in bounding box: # # http://augusttown.blogspot.co.at/2010/08/mysterious-bbox-parameter-in-web.html bbox_values = low_value.split(",") if len(bbox_values) != 4 and (wfs_version == "1.0.0" or len(bbox_values) != 5): return wfs_exception(request, "InvalidParameterValue", "bbox", value) try: bbox_has_crs = len(bbox_values) == 5 bbox_crs = CRS(bbox_values[4]) if bbox_has_crs else crs if bbox_crs.crsid == "CRS84": # we and GeoDjango operate in longitude/latitude mode, so ban CRS84 bbox = Polygon.from_bbox( (float(bbox_values[1]), float(bbox_values[0]), float(bbox_values[3]), float(bbox_values[2]))) bbox_crs = WGS84_CRS else: bbox = Polygon.from_bbox( (float(bbox_values[0]), float(bbox_values[1]), float(bbox_values[2]), float(bbox_values[3]))) bbox.set_srid(bbox_crs.srid) except: return wfs_exception(request, "InvalidParameterValue", "maxfeatures", value) elif low_key == "srsname": try: crs = CRS(low_value) if crs.crsid == "CRS84": # we and GeoDjango operate in longitude/latitude mode, so ban CRS84 crs = WGS84_CRS except: return wfs_exception(request, "InvalidParameterValue", "maxfeatures", value) # This is for the case, that srsname is hit after the bbox parameter above if bbox and not bbox_has_crs: bbox.set_srid(crs.srid) elif low_key == "filter": filtr = low_value elif low_key == "outputformat": if low_value in ALL_JSON_OUTPUT_FORMATS: outputFormat = JSON_OUTPUT_FORMAT elif low_value in ALL_XML_OUTPUT_FORMATS: outputFormat = XML_OUTPUT_FORMAT else: return wfs_exception(request, "InvalidParameterValue", "outputformat", value) if propertyname is not None: raise NotImplementedError if featureversion is not None: raise NotImplementedError if filtr is not None: raise NotImplementedError result_bbox = None # If FeatureID is present we return every feature on the list of ID's if featureid is not None: feature_list = [] # we assume every feature is identified by its Featuretype name + its object ID like "name.id" for feature in featureid.split(","): try: ftname, fid = get_feature_from_parameter(feature) except ValueError: return wfs_exception(request, "InvalidParameterValue", "featureid", feature) try: ft = service.featuretype_set.get(name=ftname) ft_crs = CRS(ft.srs) try: geom_field = ft.find_first_geometry_field() if geom_field is None: return wfs_exception(request, "NoGeometryField", "feature") flter = json.loads(ft.query) objs = ft.model.model_class().objects if bbox: bbox_args = {geom_field + "__bboverlaps": bbox} objs = objs.filter(**bbox_args) if crs.srid != ft_crs.srid: objs = objs.annotate( xform=Transform(geom_field, crs.srid)) geom_field = "xform" if outputFormat == JSON_OUTPUT_FORMAT: objs = objs.annotate(geojson=AsGeoJSON(geom_field)) else: objs = objs.annotate(gml=AsGML(geom_field)) if flter: objs = objs.filter(**flter) f = objs.filter(id=fid) bb_res = f.aggregate(Extent(geom_field))[geom_field + '__extent'] if log.getEffectiveLevel() <= logging.DEBUG: log.debug("Bounding box for feature [%s] is [%s]" % (feature, bb_res)) if result_bbox is None: result_bbox = bb_res else: result_bbox = (min(result_bbox[0], bb_res[0]), min(result_bbox[1], bb_res[1]), max(result_bbox[2], bb_res[2]), max(result_bbox[3], bb_res[3])) feature_list.append((ft, f[0])) except: log.exception("caught exception in request [%s %s?%s]", request.method, request.path, request.environ['QUERY_STRING']) return wfs_exception(request, "MalformedJSONQuery", "query") except FeatureType.DoesNotExist: return wfs_exception(request, "InvalidParameterValue", "featureid", feature) # If FeatureID isn't present we rely on TypeName and return every feature present it the requested FeatureTypes elif typename is not None: feature_list = type_feature_iter() for typen in typename.split(","): try: ft = service.featuretype_set.get(name__iexact=typen) ft_crs = CRS(ft.srs) except FeatureType.DoesNotExist: return wfs_exception(request, "InvalidParameterValue", "typename", typen) try: geom_field = ft.find_first_geometry_field() if geom_field is None: return wfs_exception(request, "NoGeometryField", "feature") flter = json.loads(ft.query) objs = ft.model.model_class().objects if bbox: bbox_args = {geom_field + "__bboverlaps": bbox} objs = objs.filter(**bbox_args) if crs.srid != ft_crs.srid: objs = objs.annotate(xform=Transform(geom_field, crs.srid)) geom_field = "xform" if outputFormat == JSON_OUTPUT_FORMAT: objs = objs.annotate(geojson=AsGeoJSON(geom_field)) else: objs = objs.annotate(gml=AsGML(geom_field)) if flter: objs = objs.filter(**flter) if resolution is not None: res_flter = ft.resolutionfilter_set.filter( min_resolution__lte=resolution).order_by( "-min_resolution").first() if res_flter: log.debug( "Applying extra filter [%s] with condition [%s] for resolution [%f]" % (res_flter, res_flter.query, resolution)) res_flter_parsed = json.loads(res_flter.query) objs = objs.filter(**res_flter_parsed) bb_res = objs.aggregate(Extent(geom_field))[geom_field + '__extent'] if log.getEffectiveLevel() <= logging.DEBUG: log.debug("Bounding box for feature type [%s] is [%s]" % (typen, bb_res)) if result_bbox is None: result_bbox = bb_res else: result_bbox = (min(result_bbox[0], bb_res[0]), min(result_bbox[1], bb_res[1]), max(result_bbox[2], bb_res[2]), max(result_bbox[3], bb_res[3])) feature_list.add_type_with_features(ft, objs) except: log.exception("caught exception in request [%s %s?%s]", request.method, request.path, request.environ['QUERY_STRING']) return wfs_exception(request, "MalformedJSONQuery", "query") else: return wfs_exception(request, "MissingParameter", "typename") if outputFormat == JSON_OUTPUT_FORMAT: return StreamingHttpResponse(streaming_content=GeoJsonIterator( service.id, crs, result_bbox, feature_list), content_type="application/json") else: context['features'] = feature_list if result_bbox: context['bbox0'] = result_bbox[0] context['bbox1'] = result_bbox[1] context['bbox2'] = result_bbox[2] context['bbox3'] = result_bbox[3] context['crs'] = crs context['version'] = wfs_version context[ 'wfs_path'] = "1.0.0/WFS-basic.xsd" if wfs_version == "1.0.0" else "1.1.0/wfs.xsd" return render(request, 'getFeature.xml', context, content_type="text/xml")
def get_queryset(self): ''' kwarg: zipcode query_params: - med_id: MedicationName id - formulations: list of Medication ids - provider_type: list of ProviderType ids - provider_category: list of ProviderCategory ids - drug_type: list of 1 character str, for drug_type in Medication - state_id: int of a state obj, used when more than one zipcode ''' med_id = self.request.query_params.get('med_id') state_id = self.request.query_params.get('state_id') provider_category_filters = self.request.query_params.getlist( 'provider_categories[]', []) provider_type_filters = self.request.query_params.getlist( 'provider_types[]', []) user = self.request.user zipcode = self.kwargs.get('zipcode') # check permission state_id, zipcode = force_user_state_id_and_zipcode( user, state_id, zipcode) try: int(med_id) except (ValueError, TypeError): return ZipCode.objects.filter(zipcode=zipcode).annotate( centroid=AsGeoJSON(Centroid('geometry')), ) provider_medication_ids = get_provider_medication_id( self.request.query_params, ) if state_id: zipcode_qs = ZipCode.objects.filter( zipcode=zipcode, state=state_id, ) else: zipcode_qs = ZipCode.objects.filter(zipcode=zipcode) zipcode_qs = zipcode_qs.annotate( active_provider_count=Count( 'providers__id', filter=Q(providers__active=True, providers__category__id__isnull=False, providers__type__id__isnull=False, providers__provider_medication__id__in= provider_medication_ids), distinct=True), total_provider_count=Count('providers__id', distinct=True), medication_levels=ArrayAgg( 'providers__provider_medication__level', filter=Q(providers__provider_medication__id__in= provider_medication_ids # noqa )), centroid=AsGeoJSON(Centroid('geometry')), ) return zipcode_qs