You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

112 lines
4.5 KiB

import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.shapereader as shpreader
from cartopy.feature import ShapelyFeature, NaturalEarthFeature
from shapely.geometry import LineString
import geopandas as gpd
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from urllib.parse import urlencode, unquote
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有来源,或者指定来源列表
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头部
)
@app.get("/getpng")
# def print_hi():
async def getpng(urls: str):
result = {
"code": 0,
"data": "aaaaaaaaa"
}
# geojson_file_path = r'C:\Users\shiys\Desktop\UPPERTT2022040500200_LINE.geojson'
# 读取 GeoJSON 数据
geojson_file_path = unquote(urls)
geojson_data = gpd.read_file(geojson_file_path)
geometries = geojson_data.geometry
# 创建图形和轴
fig = plt.figure(figsize=(10, 10))
plt.rcParams['font.family'] = 'SimHei'
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# 设置地图的范围
ax.set_extent([60, 150, 10, 58], crs=ccrs.PlateCarree())
# 陆地
ax.add_feature(NaturalEarthFeature('physical', 'land', '50m', edgecolor='#cfedf7', facecolor='white'))
# 边框
ax.add_feature(NaturalEarthFeature('cultural', 'admin_0_countries', '50m', edgecolor='#2b94d7', facecolor='none',linewidth=0.2))
# 设置海洋颜色
ocean_color = '#cfedf7' # 海洋蓝色
ax.add_feature(cfeature.OCEAN.with_scale('50m'), facecolor=ocean_color)
# 读取并绘制省份边界
# 指定shapefile路径
china_admin_file = shpreader.Reader(r'D:\zxmTest\ZxmWorkJava\GYJ\GYX2\python\python\doc\china.shp')
print(china_admin_file.records());
for record in china_admin_file.records():
# 使用geometries()方法获取几何信息
geometry = record.geometry
ax.add_geometries([geometry], ccrs.PlateCarree(), facecolor='white', edgecolor='#c6aecb',linewidth=0.2)
# 提取省份名称
province_name = record.attributes['NAME'] # 这里的'NAME_1'取决于你的shapefile中的字段名
# 计算省份中心点
center_x, center_y = geometry.centroid.x, geometry.centroid.y
# 在地图上添加省份名称
ax.text(center_x, center_y, province_name, transform=ccrs.PlateCarree(),fontsize=4, color='#43a2ff', zorder=2)
# 创建 ShapelyFeature(等高线)
geo_feature = ShapelyFeature(geometries, ccrs.PlateCarree(), edgecolor='#0000ff', facecolor='none',linewidth=0.3, zorder=5)
# 提取几何对象和对应的数值
geometriespoint = geojson_data['geometry']
values = geojson_data['VAL']
# 在等高线上标注数值
for index, (geometrypoint, value) in enumerate(zip(geometriespoint, values)):
if isinstance(geometrypoint, LineString):
# 解析 LINESTRING Z 数据
parsed_coords = str(geometries[index]).replace("LINESTRING Z (", "").replace(")", "")
parsed_coords = [tuple(map(float, coord.strip().split())) for coord in parsed_coords.split(",")]
first_coord = parsed_coords[0]
x, y, z = first_coord
# 计算线段的中点
midpoint = geometrypoint.interpolate(0.5, normalized=True)
if 60 < midpoint.x < 150 and 10 < midpoint.y < 58:
# 标注数值
bbox_props = dict(boxstyle="round,pad=0", facecolor="white", edgecolor="none", lw=1)
ax.text(midpoint.x, midpoint.y, f"{z}", fontsize=4, ha='center', va='center', color='#0000ff', bbox=bbox_props, zorder=8)
# 添加 GeoJSON 特征
ax.add_feature(geo_feature)
# 保存为 PNG 图像
output_file_path = 'D:\zxmTest\pngs\output.png'
plt.savefig(output_file_path, dpi=600,bbox_inches='tight', pad_inches=0)
# 显示图形
# plt.show()
result['code'] = 1
result['data'] = output_file_path
# except:
# result['code'] = 0
# result['data'] = "文件转换图片失败,请重试"
return result
if __name__ == '__main__':
# print_hi()
# china_admin_file = shpreader.Reader(r'D:\javaproject\weather\weather\python\python\doc\china.shp', encoding='utf-8')
#print(cartopy.config)
print("---------")
# print(china_admin_file.records())
# print("1111111111111")
# for record in china_admin_file.records():
# a=1