Browse Source

优化空间分析

baoyubo 9 months ago
parent
commit
170a90a2b4
2 changed files with 59 additions and 30 deletions
  1. 2 1
      routers/api/spatialAnalysis/__init__.py
  2. 57 29
      utils/spatial/__init__.py

+ 2 - 1
routers/api/spatialAnalysis/__init__.py

@@ -41,7 +41,7 @@ async def mine(request: Request,body = Depends(remove_xss_json),db: Session = De
         # 行政镇、行政村数据
         # town_village_data,town_count,village_count = count_town_village(from_data.location,db)
         # town_village_data,town_count = get_town_list(body)
-        town_village_data,town_count = get_town_village_list(body,db)
+        town_village_data,town_count,village_count = get_town_village_list(body,db)
         # emergency_expert_count = count_emergency_expert(from_data.location,db)
         # emergency_management_count = count_emergency_management(from_data.location,db)
         hospital_list = get_hospital_list(body,db)
@@ -53,6 +53,7 @@ async def mine(request: Request,body = Depends(remove_xss_json),db: Session = De
             "data": {
                 "townData":town_village_data,
                 "townCount":town_count,
+                "villageCount":village_count,
                 # "villageCount":village_count,
                 "populationSize":0,
                 "areaSize":0,

+ 57 - 29
utils/spatial/__init__.py

@@ -4,11 +4,41 @@
 from common.BigDataCenterAPI import *
 from models import *
 from sqlalchemy import  text
-
+from sqlalchemy import func
 from shapely.geometry import Polygon, MultiPolygon
 from shapely.ops import unary_union
 import json
 
+
+def convert_to_polygon(points):
+    # 将点的列表转换为POLYGON格式的字符串
+    polygon_str = "POLYGON(("
+    for point in points:
+        # 假设点的顺序是经度(x),纬度(y)
+        polygon_str += f"{point['y']} {point['x']}, "
+    # 移除最后一个逗号和空格,然后添加闭合点和结束括号
+    polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
+    return polygon_str
+
+
+def get_town_list2(location_list:list,db):
+    resutl = []
+    for location in location_list:
+        location = convert_to_polygon(location)
+        sql = text(f"""SELECT DISTINCT `name`,geometry,properties,pac FROM tp_geojson_data_zj WHERE ST_Intersects(geometry,ST_PolygonFromText( '{location}', 4326 ))""")
+
+        resutl+=db.execute(sql).all()
+    return resutl
+
+def get_village_list(location_list:list,db,pac=''):
+    resutl = []
+    for location in location_list:
+        location = convert_to_polygon(location)
+        sql = text(f"""SELECT DISTINCT `name`,geometry,properties,pac FROM (select * from tp_geojson_data_cj_sq  {pac})A WHERE ST_Intersects(geometry,ST_PolygonFromText( '{location}', 4326 )) """)
+
+        resutl+=db.execute(sql).all()
+    return resutl
+
 def get_town_list(locations,):
     # 初始化一个空的MultiPolygon来容纳所有多边形
 
@@ -59,41 +89,48 @@ def get_town_list(locations,):
 def get_town_village_list(locations,db):
     # 初始化一个空的MultiPolygon来容纳所有多边形
 
-    multi_polygon = MultiPolygon()
-
-    # 遍历每个位置,创建多边形并添加到multi_polygon中
-    for location in locations:
-        # 将边界列表转换为Polygon
-        polygon = Polygon([(item['x'], item['y']) for item in location])
-        multi_polygon = multi_polygon.union(polygon)
-
-    intersected_towns = TpZjGeoJSONData.query.filter(
-        db.func.ST_Intersects(TpZjGeoJSONData.geometry, multi_polygon) == True
-    ).all()
+    # multi_polygon = MultiPolygon()
+    #
+    # # 遍历每个位置,创建多边形并添加到multi_polygon中
+    # for location in locations:
+    #     # 将边界列表转换为Polygon
+    #     polygon = Polygon([(item['x'], item['y']) for item in location])
+    #     multi_polygon = multi_polygon.union(polygon)
 
+    # intersected_towns = db.query(TpZjGeoJSONData).filter(
+    #     func.ST_Intersects(TpZjGeoJSONData.geometry, multi_polygon) == True
+    # ).all()
+    intersected_towns = get_town_list2(locations,db)
 
     # 初始化一个空列表来存储结果
     intersected_names_and_pacs = []
+    town_count = 0
+    village_count = 0
     for town in intersected_towns:
+        town_count+=1
         town_pac = town.pac[:-3]
+        properties = json.loads(town.properties)
         town_data = {
             "townName": town.name,
             "code": town.pac,
             "populationSize": 0,  # 假设值,需要从数据中获取
-            "areaSize": town.geometry.area,  # 交集区域的面积
+            "areaSize": properties['GEO_AREA'],  # 交集区域的面积
             "GDP": 0  # 假设值,需要从数据中获取
         }
 
-        intersected_villages = TpCjSqGeoJSONData.query.filter(
-            db.func.ST_Intersects(TpCjSqGeoJSONData.geometry, multi_polygon) == True
-        ).filter(TpCjSqGeoJSONData.pac.like(f'{town_pac}%')).all()
+        # intersected_villages = db.query(TpCjSqGeoJSONData).filter(
+        #     func.ST_Intersects(TpCjSqGeoJSONData.geometry, multi_polygon) == True
+        # ).filter(TpCjSqGeoJSONData.pac.like(f'{town_pac}%')).all()
+        intersected_villages = get_village_list(locations,db,pac=f""" where pac like '{town_pac}%'""")
         intersected_villages_names_and_pacs = []
         for village in intersected_villages:
+            village_count += 1
+            properties = json.loads(village.properties)
             village_data = {
                 "villageName": village.name,
                 "code": village.pac,
                 "populationSize": 0,  # 假设值,需要从数据中获取
-                "areaSize": village.geometry.area,  # 交集区域的面积
+                "areaSize": properties['GEO_AREA'],  # 交集区域的面积
                 "GDP": 0  # 假设值,需要从数据中获取
             }
             intersected_villages_names_and_pacs.append(village_data)
@@ -102,7 +139,7 @@ def get_town_village_list(locations,db):
             town_data['villageCount'] = len(intersected_villages_names_and_pacs)
         intersected_names_and_pacs.append(town_data)
 
-    return intersected_names_and_pacs, len(intersected_names_and_pacs)
+    return intersected_names_and_pacs, town_count,village_count
 # import geopandas as gpd
 # from shapely.geometry import Polygon
 #
@@ -133,16 +170,6 @@ def get_town_village_list(locations,db):
 
 
 
-def convert_to_polygon(points):
-    # 将点的列表转换为POLYGON格式的字符串
-    polygon_str = "POLYGON(("
-    for point in points:
-        # 假设点的顺序是经度(x),纬度(y)
-        polygon_str += f"{point['y']} {point['x']}, "
-    # 移除最后一个逗号和空格,然后添加闭合点和结束括号
-    polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
-    return polygon_str
-
 def count_town_village(location_list:list,db):
     town_count = 0
     town_list = []
@@ -234,4 +261,5 @@ def get_waterlogged_roads_list(location_list:list,db):
         sql = text(f"""SELECT flood_name as `name`,lng as longitude,lat as latitude,4 AS `dataType` FROM mid_waterlogged_roads WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', lat, ' ', lng, ')'), 4326))""")
 
         resutl+=db.execute(sql).all()
-    return resutl
+    return resutl
+