__init__.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 shapely.geometry import Polygon, MultiPolygon
  7. from shapely.ops import unary_union
  8. import json
  9. def get_town_list(locations,):
  10. # 初始化一个空的MultiPolygon来容纳所有多边形
  11. multi_polygon = MultiPolygon()
  12. # 遍历每个位置,创建多边形并添加到multi_polygon中
  13. for location in locations:
  14. # 将边界列表转换为Polygon
  15. polygon = Polygon([(item['x'], item['y']) for item in location])
  16. multi_polygon = multi_polygon.union(polygon)
  17. # 将GeoJSON数据转换为字典
  18. with open('/home/python3/xh_twapi01/utils/spatial/zj_geojson.json', 'r', encoding='utf-8') as file:
  19. geojson = json.load(file)
  20. # 假设GeoJSON数据是一个FeatureCollection
  21. features = geojson.get('features', [])
  22. # 初始化一个空列表来存储结果
  23. intersected_names_and_pacs = []
  24. # 遍历GeoJSON中的每个Feature,计算交集
  25. for feature in features:
  26. geom = feature['geometry']
  27. if 'coordinates' in geom:
  28. # 将GeoJSON Polygon转换为shapely Polygon
  29. if geom['type'] == 'Polygon':
  30. polygon = Polygon(geom['coordinates'][0])
  31. intersection = polygon.intersection(multi_polygon)
  32. elif geom['type'] == 'MultiPolygon':
  33. multi_polygon_feature = MultiPolygon([Polygon(coords[0]) for coords in geom['coordinates']])
  34. intersection = multi_polygon_feature.intersection(multi_polygon)
  35. else:
  36. continue # 跳过非Polygon和非MultiPolygon类型的几何对象
  37. if not intersection.is_empty:
  38. properties = feature['properties']
  39. intersected_names_and_pacs.append({
  40. "townName": properties.get('NAME', ''),
  41. "code": properties.get('PAC', ''),
  42. "populationSize": 0, # 假设值,需要从数据中获取
  43. "areaSize": round(intersection.area, 2), # 交集区域的面积
  44. "GDP": 0 # 假设值,需要从数据中获取
  45. })
  46. return intersected_names_and_pacs, len(intersected_names_and_pacs)
  47. # import geopandas as gpd
  48. # from shapely.geometry import Polygon
  49. #
  50. #
  51. #
  52. # def get_town_list(locations):
  53. # # 读取GeoJSON文件为GeoDataFrame
  54. # gdf = gpd.read_file('zj_geojson.json')
  55. # gdf = gdf.set_crs("EPSG:4326", allow_override=True)
  56. #
  57. # # 初始化一个空的GeoDataFrame来容纳所有多边形
  58. # multi_polygon_gdf = gpd.GeoDataFrame(crs=gdf.crs)
  59. #
  60. # # 遍历每个位置,创建多边形并添加到multi_polygon_gdf中
  61. # for location in locations:
  62. # # 将边界列表转换为Polygon
  63. # polygon = Polygon([(item['x'], item['y']) for item in location])
  64. # # 将多边形添加到multi_polygon_gdf中
  65. # multi_polygon_gdf = multi_polygon_gdf.append(gpd.GeoDataFrame([1], geometry=[polygon], crs=gdf.crs))
  66. #
  67. # # 使用overlay函数来找出相交的区域
  68. # intersected = gpd.overlay(gdf, multi_polygon_gdf, how='intersection')
  69. #
  70. # # 获取相交区域的名称和PAC
  71. # 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]
  72. #
  73. # return intersected_names_and_pacs,len(intersected_names_and_pacs)
  74. def convert_to_polygon(points):
  75. # 将点的列表转换为POLYGON格式的字符串
  76. polygon_str = "POLYGON(("
  77. for point in points:
  78. # 假设点的顺序是经度(x),纬度(y)
  79. polygon_str += f"{point['y']} {point['x']}, "
  80. # 移除最后一个逗号和空格,然后添加闭合点和结束括号
  81. polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
  82. return polygon_str
  83. def count_town_village(location_list:list,db):
  84. town_count = 0
  85. town_list = []
  86. village_count = 0
  87. village_list = []
  88. result = []
  89. url = 'https://19.15.75.180:8581/GatewayMsg/http/api/proxy/invoke'
  90. service_code= 'YZT1685418808667'
  91. service_info = db.query(OneShareApiEntity).filter(OneShareApiEntity.servercode == service_code).first()
  92. signTime = str(GetTime() // 1000)
  93. nonce = GetNonce(5)
  94. sign = GetSign(signTime, nonce, service_info.passtoken)
  95. headers = {
  96. # 'Content-Type': 'application/json',
  97. 'x-tif-signature': sign,
  98. 'x-tif-timestamp': signTime,
  99. 'x-tif-nonce': nonce,
  100. 'x-tif-paasid': service_info.passid,
  101. 'x-tif-serviceId': service_code
  102. }
  103. response = requests.post(url=url, headers=headers, json=location_list, verify=False)
  104. if response.status_code==200:
  105. data_list = response.json()['data']
  106. for data in data_list:
  107. township = data['townshipCode']
  108. if township not in town_list:
  109. town_count+=1
  110. town_list.append(township)
  111. # result.append({'township':data['township'],"townshipCode":data['townshipCode'],"villages":[]})
  112. result.append({'township':data['township'],"townshipCode":data['townshipCode'],"village":'-',"villageCode":'-',"populationSize":0,"areaSize":0,"GDP":0})
  113. village = data['villageCode']
  114. if village not in village_list:
  115. village_count+=1
  116. village_list.append(village)
  117. # for town in result:
  118. # if town['townshipCode']==data['townshipCode']:
  119. # town["villages"].append({'village': data['village'], "villageCode": data['villageCode']})
  120. result.append({'township':data['township'],"townshipCode":data['townshipCode'],'village': data['village'], "villageCode": data['villageCode'],"populationSize":0,"areaSize":0,"GDP":0})
  121. return result,town_count,village_count
  122. def count_emergency_expert(location_list:list,db):
  123. location = convert_to_polygon(location_list)
  124. sql = text(f"""SELECT * FROM emergency_expert WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  125. return len(db.execute(sql).all())
  126. def count_emergency_management(location_list: list, db):
  127. location = convert_to_polygon(location_list)
  128. sql = text(f"""SELECT DISTINCT management_unit FROM `rescue_materia` WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  129. return len(db.execute(sql).all())
  130. def get_hospital_list(location_list:list,db):
  131. resutl = []
  132. for location in location_list:
  133. location = convert_to_polygon(location)
  134. 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))""")
  135. resutl+=db.execute(sql).all()
  136. return resutl
  137. def get_emergency_shelter_list(location_list:list,db):
  138. resutl = []
  139. for location in location_list:
  140. location = convert_to_polygon(location)
  141. 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))""")
  142. resutl+=db.execute(sql).all()
  143. return resutl
  144. def get_waterlogged_roads_list(location_list:list,db):
  145. resutl = []
  146. for location in location_list:
  147. location = convert_to_polygon(location)
  148. 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))""")
  149. resutl+=db.execute(sql).all()
  150. return resutl