__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from common.BigDataCenterAPI import *
  4. from models import *
  5. from sqlalchemy import text
  6. from sqlalchemy import func
  7. from shapely.geometry import Polygon, MultiPolygon
  8. from shapely.ops import unary_union
  9. import json
  10. def convert_to_polygon(points):
  11. # 将点的列表转换为POLYGON格式的字符串
  12. polygon_str = "POLYGON(("
  13. for point in points:
  14. # 假设点的顺序是经度(x),纬度(y)
  15. polygon_str += f"{point['y']} {point['x']}, "
  16. # 移除最后一个逗号和空格,然后添加闭合点和结束括号
  17. polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
  18. return polygon_str
  19. def get_town_list2(location_list:list,db):
  20. resutl = []
  21. for location in location_list:
  22. location = convert_to_polygon(location)
  23. sql = text(f"""SELECT DISTINCT `name`,geometry,properties,pac FROM tp_geojson_data_zj WHERE ST_Intersects(geometry,ST_PolygonFromText( '{location}', 4326 ))""")
  24. resutl+=db.execute(sql).all()
  25. return resutl
  26. def get_village_list(location_list:list,db,pac=''):
  27. resutl = []
  28. for location in location_list:
  29. location = convert_to_polygon(location)
  30. 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 )) """)
  31. resutl+=db.execute(sql).all()
  32. return resutl
  33. def get_town_list(locations,):
  34. # 初始化一个空的MultiPolygon来容纳所有多边形
  35. multi_polygon = MultiPolygon()
  36. # 遍历每个位置,创建多边形并添加到multi_polygon中
  37. for location in locations:
  38. # 将边界列表转换为Polygon
  39. polygon = Polygon([(item['x'], item['y']) for item in location])
  40. multi_polygon = multi_polygon.union(polygon)
  41. # 将GeoJSON数据转换为字典
  42. with open('/home/python3/zj_geojson.json', 'r', encoding='utf-8') as file:
  43. geojson = json.load(file)
  44. # 假设GeoJSON数据是一个FeatureCollection
  45. features = geojson.get('features', [])
  46. # 初始化一个空列表来存储结果
  47. intersected_names_and_pacs = []
  48. # 遍历GeoJSON中的每个Feature,计算交集
  49. for feature in features:
  50. geom = feature['geometry']
  51. if 'coordinates' in geom:
  52. # 将GeoJSON Polygon转换为shapely Polygon
  53. if geom['type'] == 'Polygon':
  54. polygon = Polygon(geom['coordinates'][0])
  55. intersection = polygon.intersection(multi_polygon)
  56. elif geom['type'] == 'MultiPolygon':
  57. multi_polygon_feature = MultiPolygon([Polygon(coords[0]) for coords in geom['coordinates']])
  58. intersection = multi_polygon_feature.intersection(multi_polygon)
  59. else:
  60. continue # 跳过非Polygon和非MultiPolygon类型的几何对象
  61. if not intersection.is_empty:
  62. properties = feature['properties']
  63. intersected_names_and_pacs.append({
  64. "townName": properties.get('NAME', ''),
  65. "code": properties.get('PAC', ''),
  66. "populationSize": 0, # 假设值,需要从数据中获取
  67. "areaSize": round(intersection.area, 2), # 交集区域的面积
  68. "GDP": 0 # 假设值,需要从数据中获取
  69. })
  70. return intersected_names_and_pacs, len(intersected_names_and_pacs)
  71. def get_town_village_list(locations,db):
  72. # 初始化一个空的MultiPolygon来容纳所有多边形
  73. # multi_polygon = MultiPolygon()
  74. #
  75. # # 遍历每个位置,创建多边形并添加到multi_polygon中
  76. # for location in locations:
  77. # # 将边界列表转换为Polygon
  78. # polygon = Polygon([(item['x'], item['y']) for item in location])
  79. # multi_polygon = multi_polygon.union(polygon)
  80. # intersected_towns = db.query(TpZjGeoJSONData).filter(
  81. # func.ST_Intersects(TpZjGeoJSONData.geometry, multi_polygon) == True
  82. # ).all()
  83. intersected_towns = get_town_list2(locations,db)
  84. # 初始化一个空列表来存储结果
  85. intersected_names_and_pacs = []
  86. town_count = 0
  87. village_count = 0
  88. for town in intersected_towns:
  89. town_count+=1
  90. town_pac = town.pac[:-3]
  91. properties = json.loads(town.properties)
  92. town_data = {
  93. "townName": town.name,
  94. "code": town.pac,
  95. "populationSize": 0, # 假设值,需要从数据中获取
  96. "areaSize": properties['GEO_AREA'], # 交集区域的面积
  97. "GDP": 0 # 假设值,需要从数据中获取
  98. }
  99. # intersected_villages = db.query(TpCjSqGeoJSONData).filter(
  100. # func.ST_Intersects(TpCjSqGeoJSONData.geometry, multi_polygon) == True
  101. # ).filter(TpCjSqGeoJSONData.pac.like(f'{town_pac}%')).all()
  102. intersected_villages = get_village_list(locations,db,pac=f""" where pac like '{town_pac}%'""")
  103. intersected_villages_names_and_pacs = []
  104. for village in intersected_villages:
  105. village_count += 1
  106. properties = json.loads(village.properties)
  107. village_data = {
  108. "villageName": village.name,
  109. "code": village.pac,
  110. "populationSize": 0, # 假设值,需要从数据中获取
  111. "areaSize": properties['GEO_AREA'], # 交集区域的面积
  112. "GDP": 0 # 假设值,需要从数据中获取
  113. }
  114. intersected_villages_names_and_pacs.append(village_data)
  115. if len(intersected_villages_names_and_pacs)>0:
  116. town_data['children']=intersected_villages_names_and_pacs
  117. town_data['villageCount'] = len(intersected_villages_names_and_pacs)
  118. intersected_names_and_pacs.append(town_data)
  119. return intersected_names_and_pacs, town_count,village_count
  120. # import geopandas as gpd
  121. # from shapely.geometry import Polygon
  122. #
  123. #
  124. #
  125. # def get_town_list(locations):
  126. # # 读取GeoJSON文件为GeoDataFrame
  127. # gdf = gpd.read_file('zj_geojson.json')
  128. # gdf = gdf.set_crs("EPSG:4326", allow_override=True)
  129. #
  130. # # 初始化一个空的GeoDataFrame来容纳所有多边形
  131. # multi_polygon_gdf = gpd.GeoDataFrame(crs=gdf.crs)
  132. #
  133. # # 遍历每个位置,创建多边形并添加到multi_polygon_gdf中
  134. # for location in locations:
  135. # # 将边界列表转换为Polygon
  136. # polygon = Polygon([(item['x'], item['y']) for item in location])
  137. # # 将多边形添加到multi_polygon_gdf中
  138. # multi_polygon_gdf = multi_polygon_gdf.append(gpd.GeoDataFrame([1], geometry=[polygon], crs=gdf.crs))
  139. #
  140. # # 使用overlay函数来找出相交的区域
  141. # intersected = gpd.overlay(gdf, multi_polygon_gdf, how='intersection')
  142. #
  143. # # 获取相交区域的名称和PAC
  144. # intersected_names_and_pacs = [{"name": row['NAME'], "pac": row['PAC'],"populationSize":0,"areaSize":0,"GDP":0} for index, row in intersected.iterrows() if 'NAME' in row and 'PAC' in row]
  145. #
  146. # return intersected_names_and_pacs,len(intersected_names_and_pacs)
  147. def count_town_village(location_list:list,db):
  148. town_count = 0
  149. town_list = []
  150. village_count = 0
  151. village_list = []
  152. result = []
  153. url = 'https://19.15.75.180:8581/GatewayMsg/http/api/proxy/invoke'
  154. service_code= 'YZT1685418808667'
  155. service_info = db.query(OneShareApiEntity).filter(OneShareApiEntity.servercode == service_code).first()
  156. signTime = str(GetTime() // 1000)
  157. nonce = GetNonce(5)
  158. sign = GetSign(signTime, nonce, service_info.passtoken)
  159. headers = {
  160. # 'Content-Type': 'application/json',
  161. 'x-tif-signature': sign,
  162. 'x-tif-timestamp': signTime,
  163. 'x-tif-nonce': nonce,
  164. 'x-tif-paasid': service_info.passid,
  165. 'x-tif-serviceId': service_code
  166. }
  167. response = requests.post(url=url, headers=headers, json=location_list, verify=False)
  168. if response.status_code==200:
  169. data_list = response.json()['data']
  170. for data in data_list:
  171. township = data['townshipCode']
  172. if township not in town_list:
  173. town_count+=1
  174. town_list.append(township)
  175. # result.append({'township':data['township'],"townshipCode":data['townshipCode'],"villages":[]})
  176. result.append({'township':data['township'],"townshipCode":data['townshipCode'],"village":'-',"villageCode":'-',"populationSize":0,"areaSize":0,"GDP":0})
  177. village = data['villageCode']
  178. if village not in village_list:
  179. village_count+=1
  180. village_list.append(village)
  181. # for town in result:
  182. # if town['townshipCode']==data['townshipCode']:
  183. # town["villages"].append({'village': data['village'], "villageCode": data['villageCode']})
  184. result.append({'township':data['township'],"townshipCode":data['townshipCode'],'village': data['village'], "villageCode": data['villageCode'],"populationSize":0,"areaSize":0,"GDP":0})
  185. return result,town_count,village_count
  186. def count_emergency_expert(location_list:list,db):
  187. location = convert_to_polygon(location_list)
  188. sql = text(f"""SELECT * FROM emergency_expert WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  189. return len(db.execute(sql).all())
  190. def count_emergency_management(location_list: list, db):
  191. location = convert_to_polygon(location_list)
  192. sql = text(f"""SELECT DISTINCT management_unit FROM `rescue_materia` WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  193. return len(db.execute(sql).all())
  194. def get_hospital_list(location_list:list,db):
  195. resutl = []
  196. for location in location_list:
  197. location = convert_to_polygon(location)
  198. sql = text(f"""SELECT hospital_name as `name`,longitude,latitude,6 AS `dataType` FROM mid_hospital WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  199. resutl+=db.execute(sql).all()
  200. return resutl
  201. def get_emergency_shelter_list(location_list:list,db):
  202. resutl = []
  203. for location in location_list:
  204. location = convert_to_polygon(location)
  205. sql = text(f"""SELECT shelter_name as `name`,lng as longitude,lat as latitude,3 AS `dataType` FROM mid_emergency_shelter WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', lat, ' ', lng, ')'), 4326))""")
  206. resutl+=db.execute(sql).all()
  207. return resutl
  208. def get_waterlogged_roads_list(location_list:list,db):
  209. resutl = []
  210. for location in location_list:
  211. location = convert_to_polygon(location)
  212. 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))""")
  213. resutl+=db.execute(sql).all()
  214. return resutl