Files changed (1) hide show
  1. app.py +750 -749
app.py CHANGED
@@ -1,749 +1,750 @@
1
- import gradio as gr
2
- import requests
3
- import json
4
- import geopandas as gpd
5
- import pandas as pd
6
- import numpy as np
7
- from shapely import geometry
8
- from shapely.geometry import Point, Polygon
9
- from shapely.geometry import Polygon, MultiPolygon
10
- import time
11
- from tqdm import tqdm
12
- import os
13
- import matplotlib
14
-
15
- import cconv
16
- import geopandas
17
- import contextily as cx
18
- import matplotlib.pyplot as plt
19
- from shapely.affinity import scale
20
-
21
- requests.packages.urllib3.disable_warnings()
22
- from datetime import datetime
23
- import math
24
- import random
25
- import plot_map
26
- import foodlist
27
- import POI_baidu_distribution
28
- import isochrone_get
29
- import seaborn as sns
30
-
31
- plot_map.set_mapboxtoken('pk.eyJ1IjoibGxsMzE5OTciLCJhIjoiY2w4anl6b2k5MGRxbjN4bXB1YzV6c3loaCJ9.ec49ySYxrKQWc5uyNHrzdA')
32
- plot_map.set_imgsavepath(os.getcwd())
33
-
34
- run_count=150
35
- run_count1=150
36
- run_count2=150
37
- run_count3=150
38
- def isochrone(contours_minutes, travel_mode_all, *coordinates_all):
39
- global run_count
40
- run_count += 1
41
- contours_minutes_all = ",".join(contours_minutes)
42
- def coords_trans(*coords):
43
- coords_all_wgs84 = []
44
- for coord_tuple in coords:
45
- for coord in coord_tuple:
46
- if coord:
47
- try:
48
- lng, lat = coord.split(',')
49
- lng_i, lat_i = cconv.bd09_to_wgs84(float(lng), float(lat))
50
- string_i = str(lng_i) + "," + str(lat_i)
51
- coords_all_wgs84.append(string_i)
52
- except (ValueError, AttributeError):
53
- print(f"Error processing coordinate: {coord}")
54
- return coords_all_wgs84
55
- coords_all_wgs84 = coords_trans(coordinates_all)
56
- long84=[]
57
- lat84=[]
58
- for coods84 in coords_all_wgs84:
59
- long84.append(coods84.split(",")[0])
60
- lat84.append(coods84.split(",")[1])
61
- min_lat=float(min(lat84))
62
- min_long=float(min(long84))
63
- max_long=float(max(long84))
64
- max_lat=float(max(lat84))
65
- long_bounds=max_long-min_long
66
- lat_bounds=max_lat-min_lat
67
- coords_lat_average=(min_lat+max_lat)/2
68
- coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
69
- long_meterdif=long_bounds*coords_delta_x/0.01
70
- lat_meterdif=lat_bounds/111*1000
71
- print(long_meterdif)
72
- print(lat_meterdif)
73
- if lat_meterdif <3000 and long_meterdif <3000:
74
- merge_polygon_gdf_all=isochrone_get.get_polygon_gdf(coords_all_wgs84,contours_minutes_all,travel_mode_all)
75
-
76
- fig = plt.figure(figsize=(14,10),dpi = 100)
77
- ax = fig.add_subplot(111)
78
- walking_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "walking"].tolist()
79
- cycle_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "cycling"].tolist()
80
- for idx, geom in merge_polygon_gdf_all['geometry'].items():
81
- if isinstance(geom, Polygon):
82
- if idx in walking_indeices:
83
- patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))
84
- elif idx in cycle_indeices:
85
- patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
86
- else:
87
- patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
88
- elif isinstance(geom, MultiPolygon):
89
- for poly in geom:
90
- if idx in walking_indeices:
91
- patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))
92
- elif idx in cycle_indeices:
93
- patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
94
- else:
95
- patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
96
- scale_factor = 2
97
- bigger_polygon = merge_polygon_gdf_all.geometry.apply(lambda x: scale(x, xfact=scale_factor, yfact=scale_factor))
98
- rec_bounds=bigger_polygon.total_bounds
99
- bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
100
- difference_x = bounds[2] - bounds[0]
101
- difference_y = bounds[3] - bounds[1]
102
- target_scale=29.7/21
103
- recent_scale=difference_x/difference_y
104
- print(recent_scale)
105
- if recent_scale>target_scale:
106
- target_Dy=difference_x*21/29.7
107
- bounds[3]=bounds[3]+(target_Dy-difference_y)/2
108
- bounds[1]=bounds[1]-(target_Dy-difference_y)/2
109
- elif recent_scale<target_scale:
110
- target_Dx=difference_y*29.7/21
111
- bounds[2]=bounds[2]+(target_Dx-difference_x)/2
112
- bounds[0]=bounds[0]-(target_Dx-difference_x)/2
113
- else:
114
- pass
115
- new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
116
- ax.set_xlim(new_bounds[0],new_bounds[2])
117
- ax.set_ylim(new_bounds[1],new_bounds[3])
118
- plt.grid(True)
119
- new_dif_x=new_bounds[2]-new_bounds[0]
120
- new_dif_y=new_bounds[3]-new_bounds[1]
121
- unit_x=new_dif_x/14
122
- unit_y=new_dif_y/10
123
- list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
124
- list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
125
- plt.xticks(list_new_x)
126
- plt.yticks(list_new_y)
127
- plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
128
- for coord_str in coords_all_wgs84:
129
- lng, lat = map(float, coord_str.split(','))
130
- rounded_lng = round(lng, 5)
131
- rounded_lat = round(lat, 5)
132
- plt.scatter(rounded_lng, rounded_lat, color='black', marker='o',s=50,zorder=3)
133
- radius_circle=unit_x/4
134
- layer_num=2
135
- centroid_x=new_bounds[0]+unit_x
136
- centroid_y=new_bounds[1]+unit_y
137
- centroid_forcircle=(centroid_x,centroid_y)
138
- circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
139
- ax.add_patch(circle)
140
- x_dataforline=[centroid_x,centroid_x]
141
- y_dataforline=[centroid_y,centroid_y+radius_circle]
142
- line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
143
- x_datafortext=centroid_x
144
- y_datafortext=centroid_y+radius_circle
145
- ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
146
- lat_average=(new_bounds[1]+new_bounds[3])/2
147
- bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
148
- text_y=bar_startpt[1]+radius_circle
149
- teztsize=10
150
- layer_num=2
151
- delta_x=abs(111*1000*0.01*math.cos(lat_average))
152
- unit_distance=unit_x*delta_x/0.01
153
- if unit_distance/2>100:
154
- nereast_num=int(unit_distance/100)*100
155
- lon_randon=unit_x*nereast_num/unit_distance
156
- barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
157
- barran_ypt=(bar_startpt[1],bar_startpt[1])
158
- barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
159
- barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
160
- barran3_ypt=(bar_startpt[1],bar_startpt[1])
161
- barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
162
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
163
- ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
164
- ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
165
- else:
166
-
167
- num=100
168
- lon100=unit_x*num/unit_distance
169
- bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
170
- bar100_ypt=(bar_startpt[1],bar_startpt[1])
171
- bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
172
- bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
173
- bar300_ypt=(bar_startpt[1],bar_startpt[1])
174
- bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
175
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
176
- ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
177
- ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
178
-
179
- plt.grid(True,zorder=1,alpha=0.5)
180
-
181
- now = datetime.now()
182
- timestamp = now.strftime("%Y%m%d%H%M%S")
183
- file_name = f"saveisochrone_{timestamp}.jpg"
184
- file_path = os.path.join(os.getcwd(), file_name)
185
- svg_name=f"saveisochrone_{timestamp}.svg"
186
- svg_path=os.path.join(os.getcwd(),svg_name)
187
- plt.savefig(file_path, dpi=300)
188
- svgfile=fig.savefig(svg_path, format='svg', transparent=True)
189
- return [file_path,svg_name,run_count,'区域选择符合限制']
190
-
191
- else:
192
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
193
- ax = blankfig.add_subplot(111)
194
- now = datetime.now()
195
- timestamp = now.strftime("%Y%m%d%H%M%S")
196
- # 构造文件名(图像)
197
- poi_file_name = f"savepoi_{timestamp}.jpg"
198
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
199
- # # 构造文件名(svg)
200
- svg_poiname=f"savepoi_{timestamp}.svg"
201
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
202
- # 保存文件
203
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
204
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
205
-
206
- return [poi_file_name,svg_poiname,run_count,"区域过大,超过3KM限制"]
207
-
208
-
209
-
210
- def random_foodchoice(loc_gradio,category_gradio,walking_min):
211
- global run_count1
212
- run_count1 += 1
213
- poi_categories = {'正餐': ['中餐厅','外国餐厅','小吃快餐店','其他'],
214
- '下午茶': ['蛋糕甜品店','咖啡厅','奶茶','其他']} #
215
-
216
- cent = loc_gradio.split(",")[1] + "," + loc_gradio.split(",")[0]
217
- query = '美食'
218
- category = category_gradio
219
- gdf_all_points=geopandas.GeoDataFrame()
220
- if category == "正餐":
221
- for tag in poi_categories[category]:
222
- gdf_cent = foodlist.get_data(query, tag, cent)
223
- print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
224
- try:
225
- gdf_cent = gdf_cent[gdf_cent['tag'].isin(["中餐厅", "外国餐厅", "小吃快餐店"])]
226
- gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
227
- except :
228
- print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
229
- continue
230
-
231
- elif category == "下午茶":
232
- for tag in poi_categories[category]:
233
- gdf_cent = foodlist.get_data(query, tag, cent)
234
- print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
235
- try:
236
- gdf_cent = gdf_cent[gdf_cent['tag'].isin(["蛋糕甜品店", "咖啡厅", "奶茶"])]
237
- gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
238
- except :
239
- print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
240
- continue
241
- gdf_all_points
242
- gdf_drop_points = gdf_all_points.drop_duplicates(subset=['name','lng_bd', 'lat_bd', 'lng_wgs84', 'lat_wgs84', 'address','province', 'city', 'area','uid'],ignore_index = True)
243
- print("全部数据加载完毕,共有{}个poi点,去重后共有{}个poi点".format(len(gdf_all_points),len(gdf_drop_points)))
244
- output_points = gdf_drop_points.drop(columns ='tag_drop')
245
- output_points = output_points.set_crs(crs= "EPSG:4326")
246
- lng , lat = cconv.bd09_to_wgs84(float(loc_gradio.split(",")[0]),float(loc_gradio.split(",")[1]))
247
- coordinates = str(lng) + "," + str(lat)
248
-
249
- travel_mode = "walking"
250
- contours_minutes =str(walking_min)
251
-
252
- gdf_isochrone = foodlist.get_isochrone_from_mapbox(travel_mode,coordinates,contours_minutes)
253
- gdf_isochrone = gdf_isochrone.set_crs(crs= "EPSG:4326")
254
- gdf_within = gpd.sjoin(output_points, gdf_isochrone, predicate='within')
255
- gdf_within = gdf_within.reset_index()
256
- print("有{}家待选店铺".format(len(gdf_within)))
257
- if len(gdf_within) == 0:
258
- final_out="None"
259
- messagebox="sorry~这附近好像没有可以觅食的地方哦,换个地方试试吧"
260
- else:
261
- output_name_list = list(gdf_within['name'])
262
- final_one = random.choice(output_name_list)
263
- row_address = gdf_within[gdf_within['name']==final_one]
264
- final_address = row_address['address'].values[0]
265
- row_rating = gdf_within[gdf_within['name']==final_one]
266
- final_rating = row_rating['overall_rating'].values[0]
267
- row_label = gdf_within[gdf_within['name']==final_one]
268
- final_label = row_label['label'].values[0]
269
- row_price = gdf_within[gdf_within['name']==final_one]
270
- final_price = row_label['price'].values[0]
271
- row_hours = gdf_within[gdf_within['name']==final_one]
272
- final_hours = row_label['shop_hours'].values[0]
273
- final_out="今天去吃 【{}】 ,位置在 【{}】\n 【其他相关信息】:{} {} {}".format(final_one,final_address,final_rating,final_label,final_hours)
274
- messagebox="运算正常"
275
- return [final_out,run_count1,messagebox]
276
-
277
-
278
- def POI_distribution(location1,location2,categories):
279
- global run_count2
280
- run_count2 += 1
281
- min_long=float(location1.split(",")[0])
282
- min_lat=float(location1.split(",")[1])
283
- max_long=float(location2.split(",")[0])
284
- max_lat=float(location2.split(",")[1])
285
- long_bounds=max_long-min_long
286
- lat_bounds=max_lat-min_lat
287
-
288
- coords_lat_average=(min_lat+max_lat)/2
289
- coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
290
- long_meterdif=long_bounds*coords_delta_x/0.01
291
- lat_meterdif=lat_bounds/111*1000
292
-
293
- print(long_meterdif)
294
- print(lat_meterdif)
295
-
296
- if lat_meterdif <3000 and long_meterdif <3000:
297
-
298
- location=[location1,location2]
299
- gdf_output=POI_baidu_distribution.POI_get(location,categories)
300
-
301
- if len(gdf_output)==0:
302
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
303
- ax = blankfig.add_subplot(111)
304
- #给文件命名
305
- # 获取当前日期时间信息
306
- now = datetime.now()
307
- timestamp = now.strftime("%Y%m%d%H%M%S")
308
- # 构造文件名(图像)
309
- poi_file_name = f"savepoi_{timestamp}.jpg"
310
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
311
- # # 构造文件名(svg)
312
- svg_poiname=f"savepoi_{timestamp}.svg"
313
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
314
- # 保存文件
315
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
316
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
317
- message_box="区域内没有该类型POI点"
318
- return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
319
- else:
320
- message_box="POI获取正常"
321
-
322
- fig = plt.figure(figsize=(14,10),dpi = 100)
323
- ax = fig.add_subplot(111)
324
-
325
- wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
326
- wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
327
- scale_factor = 3
328
-
329
- rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
330
- wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
331
- wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
332
- wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
333
-
334
- # points_bounds = gdf_output.total_bounds
335
- # scale_factor = 3
336
- # rec_bounds = [points_bounds[0] - (points_bounds[2] - points_bounds[0])/scale_factor,
337
- # points_bounds[1] - (points_bounds[3] - points_bounds[1])/scale_factor,
338
- # points_bounds[2] + (points_bounds[2] - points_bounds[0])/scale_factor,
339
- # points_bounds[3] + (points_bounds[3] - points_bounds[1])/scale_factor]
340
-
341
- bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
342
- difference_x = bounds[2] - bounds[0]
343
- difference_y = bounds[3] - bounds[1]
344
- target_scale=29.7/21
345
- recent_scale=difference_x/difference_y
346
- print(recent_scale)
347
- if recent_scale>target_scale:
348
- target_Dy=difference_x*21/29.7
349
- bounds[3]=bounds[3]+(target_Dy-difference_y)/2
350
- bounds[1]=bounds[1]-(target_Dy-difference_y)/2
351
- elif recent_scale<target_scale:
352
- target_Dx=difference_y*29.7/21
353
- bounds[2]=bounds[2]+(target_Dx-difference_x)/2
354
- bounds[0]=bounds[0]-(target_Dx-difference_x)/2
355
- else:
356
- pass
357
- new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
358
-
359
- ax.set_xlim(new_bounds[0],new_bounds[2])
360
- ax.set_ylim(new_bounds[1],new_bounds[3])
361
-
362
- new_dif_x=new_bounds[2]-new_bounds[0]
363
- new_dif_y=new_bounds[3]-new_bounds[1]
364
- unit_x=new_dif_x/14
365
- unit_y=new_dif_y/10
366
- list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
367
- list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
368
- plt.xticks(list_new_x)
369
- plt.yticks(list_new_y)
370
- plt.grid(True,zorder=1,alpha=0.5)
371
- plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
372
- grouped = gdf_output.groupby('category_english')
373
- for group_name, group_data in grouped:
374
- ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
375
-
376
- rec_xy=(wgsmin_long,wgsmin_lat)
377
- rec_width=wgsmax_long-wgsmin_long
378
- rec_height=wgsmax_lat- wgsmin_lat
379
- seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
380
- ax.add_patch(seclected_area)
381
- # rec_xy=(points_bounds[0],points_bounds[1])
382
- # rec_width=points_bounds[2]-points_bounds[0]
383
- # rec_height=points_bounds[3]-points_bounds[1]
384
- # seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
385
- # ax.add_patch(seclected_area)
386
-
387
- radius_circle=unit_x/4
388
- layer_num=2
389
- centroid_x=new_bounds[0]+unit_x
390
- centroid_y=new_bounds[1]+unit_y
391
- centroid_forcircle=(centroid_x,centroid_y)
392
- circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
393
- ax.add_patch(circle)
394
- x_dataforline=[centroid_x,centroid_x]
395
- y_dataforline=[centroid_y,centroid_y+radius_circle]
396
- line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
397
- x_datafortext=centroid_x
398
- y_datafortext=centroid_y+radius_circle
399
- ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
400
- lat_average=(new_bounds[1]+new_bounds[3])/2
401
- bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
402
- text_y=bar_startpt[1]+radius_circle
403
- teztsize=10
404
- layer_num=2
405
-
406
- delta_x=abs(111*1000*0.01*math.cos(lat_average))
407
-
408
- unit_distance=unit_x*delta_x/0.01
409
- if unit_distance/2>100:
410
- nereast_num=int(unit_distance/100)*100
411
- lon_randon=unit_x*nereast_num/unit_distance
412
- barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
413
- barran_ypt=(bar_startpt[1],bar_startpt[1])
414
- barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
415
- barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
416
- barran3_ypt=(bar_startpt[1],bar_startpt[1])
417
- barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
418
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
419
- ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
420
- ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
421
- else:
422
- num=100
423
- lon100=unit_x*num/unit_distance
424
- bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
425
- bar100_ypt=(bar_startpt[1],bar_startpt[1])
426
- bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
427
- bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
428
- bar300_ypt=(bar_startpt[1],bar_startpt[1])
429
- bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
430
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
431
- ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
432
- ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
433
- ax.legend(title='category_english', loc='upper right')
434
-
435
-
436
-
437
- now = datetime.now()
438
- timestamp = now.strftime("%Y%m%d%H%M%S")
439
- poi_file_name = f"savepoi_{timestamp}.jpg"
440
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
441
- svg_poiname=f"savepoi_{timestamp}.svg"
442
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
443
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
444
- svgpoifile=fig.savefig(svg_poipath, format='svg', transparent=True)
445
-
446
- return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
447
-
448
- else:
449
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
450
- ax = blankfig.add_subplot(111)
451
- now = datetime.now()
452
- timestamp = now.strftime("%Y%m%d%H%M%S")
453
- poi_file_name = f"savepoi_{timestamp}.jpg"
454
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
455
- svg_poiname=f"savepoi_{timestamp}.svg"
456
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
457
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
458
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
459
- message_box="None"
460
-
461
- return [poi_file_name,svg_poiname,run_count2,"区域过大,超过3KM限制",message_box]
462
-
463
-
464
- def POI_kernel(location1,location2,category):
465
-
466
- global run_count3
467
- run_count3 += 1
468
- min_long=float(location1.split(",")[0])
469
- min_lat=float(location1.split(",")[1])
470
- max_long=float(location2.split(",")[0])
471
- max_lat=float(location2.split(",")[1])
472
- long_bounds=max_long-min_long
473
- lat_bounds=max_lat-min_lat
474
- coords_lat_average=(min_lat+max_lat)/2
475
- coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
476
- long_meterdif=long_bounds*coords_delta_x/0.01
477
- lat_meterdif=lat_bounds/111*1000
478
-
479
- print(long_meterdif)
480
- print(lat_meterdif)
481
-
482
- if lat_meterdif <3000 and long_meterdif <3000:
483
-
484
- categories=[category]
485
- location=[location1,location2]
486
- gdf_output=POI_baidu_distribution.POI_get(location,categories)
487
-
488
- if len(gdf_output)==0:
489
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
490
- ax = blankfig.add_subplot(111)
491
- #给文件命名
492
- # 获取当前日期时间信息
493
- now = datetime.now()
494
- timestamp = now.strftime("%Y%m%d%H%M%S")
495
- # 构造文件名(图像)
496
- poi_file_name = f"savepoi_{timestamp}.jpg"
497
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
498
- # # 构造文件名(svg)
499
- svg_poiname=f"savepoi_{timestamp}.svg"
500
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
501
- # 保存文件
502
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
503
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
504
- message_box="区域内没有该类型POI点"
505
- return [poi_file_name,svg_poiname,run_count3,'区域选择符合限制',message_box]
506
- else:
507
- message_box="POI获取正常"
508
-
509
- fig = plt.figure(figsize=(14,10),dpi = 100)
510
- ax = fig.add_subplot(111)
511
- # points_bounds = gdf_output.total_bounds
512
- # scale_factor = 3
513
-
514
- # rec_bounds = [points_bounds[0] - (points_bounds[2] - points_bounds[0])/scale_factor,
515
- # points_bounds[1] - (points_bounds[3] - points_bounds[1])/scale_factor,
516
- # points_bounds[2] + (points_bounds[2] - points_bounds[0])/scale_factor,
517
- # points_bounds[3] + (points_bounds[3] - points_bounds[1])/scale_factor]
518
-
519
- wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
520
- wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
521
- scale_factor = 3
522
- rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
523
- wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
524
- wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
525
- wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
526
-
527
- bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
528
- difference_x = bounds[2] - bounds[0]
529
- difference_y = bounds[3] - bounds[1]
530
- target_scale=29.7/21
531
- recent_scale=difference_x/difference_y
532
- print(recent_scale)
533
- if recent_scale>target_scale:
534
- target_Dy=difference_x*21/29.7
535
- bounds[3]=bounds[3]+(target_Dy-difference_y)/2
536
- bounds[1]=bounds[1]-(target_Dy-difference_y)/2
537
- elif recent_scale<target_scale:
538
- target_Dx=difference_y*29.7/21
539
- bounds[2]=bounds[2]+(target_Dx-difference_x)/2
540
- bounds[0]=bounds[0]-(target_Dx-difference_x)/2
541
- else:
542
- pass
543
- new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
544
-
545
- ax.set_xlim(new_bounds[0],new_bounds[2])
546
- ax.set_ylim(new_bounds[1],new_bounds[3])
547
-
548
- new_dif_x=new_bounds[2]-new_bounds[0]
549
- new_dif_y=new_bounds[3]-new_bounds[1]
550
- unit_x=new_dif_x/14
551
- unit_y=new_dif_y/10
552
- list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
553
- list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
554
- plt.xticks(list_new_x)
555
- plt.yticks(list_new_y)
556
-
557
- plt.grid(True,zorder=1,alpha=0.5)
558
-
559
- plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
560
- grouped = gdf_output.groupby('category_english')
561
- for group_name, group_data in grouped:
562
- ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
563
-
564
- sns.kdeplot(gdf_output,x="lng_wgs84",y="lat_wgs84",fill=True,alpha=.5,hue='category_us',legend=False,color="grey") #thresh=0, levels=100, cmap="mako"
565
-
566
- radius_circle=unit_x/4
567
- layer_num=2
568
- centroid_x=new_bounds[0]+unit_x
569
- centroid_y=new_bounds[1]+unit_y
570
- centroid_forcircle=(centroid_x,centroid_y)
571
- circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
572
- ax.add_patch(circle)
573
-
574
- x_dataforline=[centroid_x,centroid_x]
575
- y_dataforline=[centroid_y,centroid_y+radius_circle]
576
- line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
577
- x_datafortext=centroid_x
578
- y_datafortext=centroid_y+radius_circle
579
- ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
580
- lat_average=(new_bounds[1]+new_bounds[3])/2
581
- bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
582
- text_y=bar_startpt[1]+radius_circle
583
- teztsize=10
584
- layer_num=2
585
- delta_x=abs(111*1000*0.01*math.cos(lat_average))
586
- unit_distance=unit_x*delta_x/0.01
587
- if unit_distance/2>100:
588
- nereast_num=int(unit_distance/100)*100
589
- lon_randon=unit_x*nereast_num/unit_distance
590
- barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
591
- barran_ypt=(bar_startpt[1],bar_startpt[1])
592
- barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
593
-
594
- barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
595
- barran3_ypt=(bar_startpt[1],bar_startpt[1])
596
- barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
597
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
598
- ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
599
- ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
600
- else:
601
- num=100
602
- lon100=unit_x*num/unit_distance
603
- bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
604
- bar100_ypt=(bar_startpt[1],bar_startpt[1])
605
- bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
606
- bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
607
- bar300_ypt=(bar_startpt[1],bar_startpt[1])
608
- bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
609
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
610
- ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
611
- ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
612
- ax.legend(title='Category')
613
-
614
-
615
- now = datetime.now()
616
- timestamp = now.strftime("%Y%m%d%H%M%S")
617
- poiker_file_name = f"savepoiker_{timestamp}.jpg"
618
- poiker_file_path = os.path.join(os.getcwd(), poiker_file_name)
619
- svgker_name=f"savepoiker_{timestamp}.svg"
620
- svgker_path=os.path.join(os.getcwd(),svgker_name)
621
- poi_ker_file= plt.savefig(poiker_file_path, dpi=300)
622
- svgkerfile=fig.savefig(svgker_path, format='svg', transparent=True)
623
- print(f"文件保存路径:{poiker_file_path}")
624
- return [poiker_file_name,svgker_name,run_count3, '区域选择符合限制',message_box]
625
-
626
- else:
627
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
628
- ax = blankfig.add_subplot(111)
629
- now = datetime.now()
630
- timestamp = now.strftime("%Y%m%d%H%M%S")
631
- poi_file_name = f"savepoi_{timestamp}.jpg"
632
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
633
- svg_poiname=f"savepoi_{timestamp}.svg"
634
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
635
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
636
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
637
- message_box="None"
638
- return [poi_file_name,svg_poiname,run_count3,"区域过大,超过3KM限制",message_box]
639
-
640
-
641
- with gr.Blocks() as demo:
642
- gr.Markdown(
643
- """
644
- # UrbanFlow-DataAnalysis
645
- 使用说明和更多关于UrbanFlow的详情请查看链接:[UrbanFlow-DataAnalysis使用说明](https://gdz6btft72.feishu.cn/docx/E0pxd8pXpo4wOQxZ8eic7iSqnXc)
646
- 如果您遇到排队较长或出图缓慢的情况,可以使用下列备用连接:[备用链接1](https://hf-mirror.com/spaces/onefan/UrbanFlow-DataAnalysis-Public) [备用链接2](https://hf-mirror.com/spaces/Mammmmmm/UrbanFlow-DataAnalysis-Public) [备用链接3](https://hf-mirror.com/spaces/Aryayaya/UrbanFlow-DataAnalysis-Public)
647
- """
648
- )
649
- with gr.Tab("等时圈分析"):
650
- with gr.Row():
651
- with gr.Column():
652
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取坐标点,并输入最多六个角点坐标来对您想生成等时圈的区域进行控制")
653
- with gr.Row():
654
- co_input = [gr.Textbox(label=f"坐标角点参数 {i}", placeholder=f"请输入参数 {i}") for i in range(1, 7)]
655
- drop1 = gr.CheckboxGroup(["walking","cycling","driving"], label="选择出行方式")
656
- drop2 = gr.CheckboxGroup(["5","10","15","20","25","30"], label="选择时间(min)")
657
- report=gr.Textbox(label="报错提醒")
658
- with gr.Column():
659
- output_img = gr.Image()
660
- output_svgpath = gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
661
- output_count=gr.Textbox(label="本页面已提供一键生图次数")
662
- cal_btn = gr.Button("Calculate")
663
- cal_btn.click(fn=isochrone, inputs=[drop2]+[drop1]+co_input, outputs=[output_img,output_svgpath,output_count,report])
664
-
665
- gr.Markdown("""
666
- ## 输入参数示例
667
- """)
668
- examples_index=[[["5"],["walking"],"113.924838,22.492807","","","",""],[["5"],["walking","cycling"],"113.923916,22.493438","113.924122,22.492887","113.924383,22.492348","113.924621,22.491827",""],[["5","10"],["walking"],"113.92366,22.493743","113.922101,22.494373","113.922159,22.494469","113.922272,22.494665","113.92242,22.494982"]]
669
- gr.Examples(examples=examples_index,inputs=[drop2]+[drop1]+co_input,outputs=output_img,fn=isochrone,label="examples")
670
-
671
- with gr.Tab("POI分布图"):
672
- with gr.Row():
673
- with gr.Column():
674
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
675
- with gr.Row():
676
- POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
677
- gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
678
- ]
679
- with gr.Row():
680
- POI_input2=gr.CheckboxGroup(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
681
- with gr.Row():
682
- with gr.Column():
683
- report=gr.Textbox(label="区域限制报错提醒")
684
- report2=gr.Textbox(label="POI数据获取报错提醒")
685
-
686
- with gr.Column():
687
- POI_output1=gr.Image(label="POI分布图")
688
- POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
689
- output_count=gr.Textbox(label="本页面已提供一键生图次数")
690
-
691
- cal_btn = gr.Button("Calculate")
692
- cal_btn.click(fn=POI_distribution, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
693
- gr.Markdown("""
694
- ## 输入参数示例
695
- """)
696
- examples_index=[["113.923428,22.491367","113.930983,22.495825",['商业服务设施-娱乐康体','公共服务设施-学校']],["113.930938,22.522402","113.942185,22.531515",['公共服务设施-学校','商业服务设施-餐饮']]]
697
- gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_distribution,label="examples")
698
-
699
-
700
- with gr.Tab("POI密度图"):
701
- with gr.Row():
702
- with gr.Column():
703
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
704
- with gr.Row():
705
- POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
706
- gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
707
- ]
708
- POI_input2=gr.Radio(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
709
- with gr.Row():
710
- with gr.Column():
711
- report=gr.Textbox(label="区域限制报错提醒")
712
- report2=gr.Textbox(label="POI数据获取报错提醒")
713
-
714
- with gr.Column():
715
- POI_output1=gr.Image(label="POI密度图")
716
- POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
717
- output_count=gr.Textbox(label="本页面已提供一键生图次数")
718
-
719
- cal_btn = gr.Button("Calculate")
720
- cal_btn.click(fn=POI_kernel, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
721
- gr.Markdown("""
722
- ## 输入参数示例
723
- """)
724
- examples_index=[["113.923428,22.491367","113.930983,22.495825",'商业服务设施-娱乐康体'],["113.930938,22.522402","113.942185,22.531515",'商业服务设施-餐饮']]
725
- gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_kernel,label="examples")
726
-
727
-
728
- with gr.Tab("今天吃什么"):
729
- with gr.Row():
730
- with gr.Column():
731
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
732
- foodlist_input1 = gr.Textbox(label="您所在位置的坐标点",placeholder="输入您所在位置的坐标点")
733
- foodlist_input2=gr.Radio(["正餐","下午茶"],label="餐食类型")
734
- foodlist_input3=gr.Slider(label="您愿意步行的距离(min)",minimum=0, maximum=10, step=1)
735
- foodlist_btn=gr.Button("开始丢骰子")
736
- foodlist_output=gr.Textbox(label="今天吃什么",lines=5)
737
- with gr.Row():
738
- output_count=gr.Textbox(label="本页面已提供店铺查询服务次数")
739
- textbox=gr.Textbox(label="报错提醒")
740
- foodlist_btn.click(fn=random_foodchoice,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=[foodlist_output,output_count,textbox])
741
- gr.Markdown("""
742
- ## 输入参数示例
743
- """)
744
- examples_index=[["113.924838,22.492807","正餐","10"],["113.924838,22.492807","下午茶","5"]]
745
- gr.Examples(examples=examples_index,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=foodlist_output,fn=random_foodchoice,label="examples")
746
-
747
-
748
- demo.launch(share=True)
749
-
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import geopandas as gpd
5
+ import pandas as pd
6
+ import numpy as np
7
+ from shapely import geometry
8
+ from shapely.geometry import Point, Polygon
9
+ import time
10
+ from tqdm import tqdm
11
+ import os
12
+ import matplotlib
13
+ import cconv
14
+ import geopandas
15
+ import matplotlib.pyplot as plt
16
+ from shapely.affinity import scale
17
+ requests.packages.urllib3.disable_warnings()
18
+ from datetime import datetime
19
+ import math
20
+ import random
21
+
22
+ import plot_map
23
+ import foodlist
24
+ import POI_baidu_distribution
25
+ import isochrone_get
26
+ import seaborn as sns
27
+ from shapely.geometry import Polygon, MultiPolygon
28
+ plot_map.set_mapboxtoken('pk.eyJ1IjoibGxsMzE5OTciLCJhIjoiY2w4anl6b2k5MGRxbjN4bXB1YzV6c3loaCJ9.ec49ySYxrKQWc5uyNHrzdA')#必须在里面设置你申请的token,直接复制此行代码无效!
29
+ plot_map.set_imgsavepath(os.getcwd())
30
+
31
+ run_count=200
32
+ run_count1=200
33
+ run_count2=200
34
+ run_count3=200
35
+
36
+ def isochrone(contours_minutes, travel_mode_all, *coordinates_all):
37
+ global run_count
38
+ run_count += 1
39
+ contours_minutes_all = ",".join(contours_minutes)
40
+ def coords_trans(*coords):
41
+ coords_all_wgs84 = []
42
+ for coord_tuple in coords:
43
+ for coord in coord_tuple:
44
+ if coord:
45
+ try:
46
+ lng, lat = coord.split(',')
47
+ lng_i, lat_i = cconv.bd09_to_wgs84(float(lng), float(lat))
48
+ string_i = str(lng_i) + "," + str(lat_i)
49
+ coords_all_wgs84.append(string_i)
50
+ except (ValueError, AttributeError):
51
+ print(f"Error processing coordinate: {coord}")
52
+ return coords_all_wgs84
53
+
54
+
55
+ coords_all_wgs84 = coords_trans(coordinates_all)
56
+
57
+
58
+ long84=[]
59
+ lat84=[]
60
+ for coods84 in coords_all_wgs84:
61
+ long84.append(coods84.split(",")[0])
62
+ lat84.append(coods84.split(",")[1])
63
+ min_lat=float(min(lat84))
64
+ min_long=float(min(long84))
65
+ max_long=float(max(long84))
66
+ max_lat=float(max(lat84))
67
+ long_bounds=max_long-min_long
68
+ lat_bounds=max_lat-min_lat
69
+ coords_lat_average=(min_lat+max_lat)/2
70
+ coords_delta_x=111*1000*0.01*math.cos(math.radians(coords_lat_average))
71
+ long_meterdif=long_bounds*coords_delta_x/0.01
72
+ lat_meterdif=lat_bounds/111*1000
73
+
74
+ print(long_meterdif)
75
+ print(lat_meterdif)
76
+
77
+ if lat_meterdif <3000 and long_meterdif <3000:
78
+
79
+ merge_polygon_gdf_all=isochrone_get.get_polygon_gdf(coords_all_wgs84,contours_minutes_all,travel_mode_all)
80
+ fig = plt.figure(figsize=(14,10),dpi = 100)
81
+ ax = fig.add_subplot(111)
82
+ walking_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "walking"].tolist()
83
+ cycle_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "cycling"].tolist()
84
+ for idx, geom in merge_polygon_gdf_all['geometry'].items():
85
+ if isinstance(geom, Polygon):
86
+ if idx in walking_indeices:
87
+ patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))#添加图形
88
+ elif idx in cycle_indeices:
89
+ patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
90
+ else:
91
+ patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
92
+ elif isinstance(geom, MultiPolygon):
93
+ for poly in geom:
94
+ if idx in walking_indeices:
95
+ patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))#添加图形
96
+ elif idx in cycle_indeices:
97
+ patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
98
+ else:
99
+ patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
100
+
101
+ scale_factor = 2
102
+ bigger_polygon = merge_polygon_gdf_all.geometry.apply(lambda x: scale(x, xfact=scale_factor, yfact=scale_factor))
103
+ rec_bounds=bigger_polygon.total_bounds
104
+ bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
105
+ difference_x = bounds[2] - bounds[0]
106
+ difference_y = bounds[3] - bounds[1]
107
+ target_scale=29.7/21
108
+ recent_scale=difference_x/difference_y
109
+ print(recent_scale)
110
+ if recent_scale>target_scale:
111
+ target_Dy=difference_x*21/29.7
112
+ bounds[3]=bounds[3]+(target_Dy-difference_y)/2
113
+ bounds[1]=bounds[1]-(target_Dy-difference_y)/2
114
+ elif recent_scale<target_scale:
115
+ target_Dx=difference_y*29.7/21
116
+ bounds[2]=bounds[2]+(target_Dx-difference_x)/2
117
+ bounds[0]=bounds[0]-(target_Dx-difference_x)/2
118
+ else:
119
+ pass
120
+ new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
121
+
122
+ ax.set_xlim(new_bounds[0],new_bounds[2])
123
+ ax.set_ylim(new_bounds[1],new_bounds[3])
124
+
125
+ plt.grid(True)
126
+ new_dif_x=new_bounds[2]-new_bounds[0]
127
+ new_dif_y=new_bounds[3]-new_bounds[1]
128
+ unit_x=new_dif_x/14
129
+ unit_y=new_dif_y/10
130
+ list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
131
+ list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
132
+ plt.xticks(list_new_x)
133
+ plt.yticks(list_new_y)
134
+ plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
135
+
136
+ for coord_str in coords_all_wgs84:
137
+ lng, lat = map(float, coord_str.split(','))
138
+ rounded_lng = round(lng, 5)
139
+ rounded_lat = round(lat, 5)
140
+ plt.scatter(rounded_lng, rounded_lat, color='black', marker='o',s=50,zorder=3)
141
+
142
+ radius_circle=unit_x/4
143
+ layer_num=2
144
+ centroid_x=new_bounds[0]+unit_x
145
+ centroid_y=new_bounds[1]+unit_y
146
+
147
+ centroid_forcircle=(centroid_x,centroid_y)
148
+ circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
149
+ ax.add_patch(circle)
150
+
151
+ x_dataforline=[centroid_x,centroid_x]
152
+ y_dataforline=[centroid_y,centroid_y+radius_circle]
153
+ line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
154
+
155
+ x_datafortext=centroid_x
156
+ y_datafortext=centroid_y+radius_circle
157
+ ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
158
+
159
+ lat_average=(new_bounds[1]+new_bounds[3])/2
160
+ bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
161
+ text_y=bar_startpt[1]+radius_circle
162
+ teztsize=10
163
+ layer_num=2
164
+
165
+ delta_x=111*1000*0.01*math.cos(math.radians(lat_average))
166
+
167
+ unit_distance=unit_x*delta_x/0.01
168
+ if unit_distance/2>100:
169
+ nereast_num=int(unit_distance/100)*100
170
+ lon_randon=unit_x*nereast_num/unit_distance
171
+
172
+ barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
173
+ barran_ypt=(bar_startpt[1],bar_startpt[1])
174
+ barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
175
+ barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
176
+ barran3_ypt=(bar_startpt[1],bar_startpt[1])
177
+ barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
178
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
179
+ ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
180
+ ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
181
+ else:
182
+ num=100
183
+ lon100=unit_x*num/unit_distance
184
+ bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
185
+ bar100_ypt=(bar_startpt[1],bar_startpt[1])
186
+ bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
187
+ bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
188
+ bar300_ypt=(bar_startpt[1],bar_startpt[1])
189
+ bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
190
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
191
+ ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
192
+ ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
193
+
194
+ plt.grid(True,zorder=1,alpha=0.5)
195
+
196
+ now = datetime.now()
197
+ timestamp = now.strftime("%Y%m%d%H%M%S")
198
+ file_name = f"saveisochrone_{timestamp}.jpg"
199
+ file_path = os.path.join(os.getcwd(), file_name)
200
+ svg_name=f"saveisochrone_{timestamp}.svg"
201
+ svg_path=os.path.join(os.getcwd(),svg_name)
202
+ plt.savefig(file_path, dpi=300)
203
+ svgfile=fig.savefig(svg_path, format='svg', transparent=True)
204
+
205
+ return [file_path,svg_name,run_count,'区域选择符合限制']
206
+
207
+ else:
208
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
209
+ ax = blankfig.add_subplot(111)
210
+ now = datetime.now()
211
+ timestamp = now.strftime("%Y%m%d%H%M%S")
212
+ poi_file_name = f"savepoi_{timestamp}.jpg"
213
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
214
+ svg_poiname=f"savepoi_{timestamp}.svg"
215
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
216
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
217
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
218
+
219
+ return [poi_file_name,svg_poiname,run_count,"区域过大,超过3KM限制"]
220
+
221
+
222
+ def random_foodchoice(loc_gradio,category_gradio,walking_min):
223
+ global run_count1
224
+ run_count1 += 1
225
+ poi_categories = {'正餐': ['中餐厅','外国餐厅','小吃快餐店','其他'],
226
+ '下午茶': ['蛋糕甜品店','咖啡厅','奶茶','其他']} #
227
+
228
+ cent = loc_gradio.split(",")[1] + "," + loc_gradio.split(",")[0]
229
+ query = '美食'
230
+
231
+ category = category_gradio
232
+ gdf_all_points=geopandas.GeoDataFrame()
233
+ if category == "正餐":
234
+ for tag in poi_categories[category]:
235
+ gdf_cent = foodlist.get_data(query, tag, cent)
236
+ print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
237
+ try:
238
+ gdf_cent = gdf_cent[gdf_cent['tag'].isin(["中餐厅", "外国餐厅", "小吃快餐店"])]
239
+ gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
240
+ except :
241
+ print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
242
+ continue
243
+
244
+ elif category == "下午茶":
245
+ for tag in poi_categories[category]:
246
+ gdf_cent = foodlist.get_data(query, tag, cent)
247
+ print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
248
+ try:
249
+ gdf_cent = gdf_cent[gdf_cent['tag'].isin(["蛋糕甜品店", "咖啡厅", "奶茶"])]
250
+ gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
251
+ except :
252
+ print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
253
+ continue
254
+
255
+ gdf_all_points
256
+ gdf_drop_points = gdf_all_points.drop_duplicates(subset=['name','lng_bd', 'lat_bd', 'lng_wgs84', 'lat_wgs84', 'address','province', 'city', 'area','uid'],ignore_index = True)
257
+ print("全部数据加载完毕,共有{}个poi点,去重后共有{}个poi点".format(len(gdf_all_points),len(gdf_drop_points)))
258
+
259
+ output_points = gdf_drop_points.drop(columns ='tag_drop')
260
+ output_points = output_points.set_crs(crs= "EPSG:4326")
261
+
262
+ lng , lat = cconv.bd09_to_wgs84(float(loc_gradio.split(",")[0]),float(loc_gradio.split(",")[1]))
263
+ coordinates = str(lng) + "," + str(lat)
264
+
265
+ travel_mode = "walking"
266
+ contours_minutes =str(walking_min)
267
+
268
+ gdf_isochrone = foodlist.get_isochrone_from_mapbox(travel_mode,coordinates,contours_minutes)
269
+ gdf_isochrone = gdf_isochrone.set_crs(crs= "EPSG:4326")
270
+
271
+
272
+ gdf_within = gpd.sjoin(output_points, gdf_isochrone, predicate='within')
273
+ gdf_within = gdf_within.reset_index()
274
+ print("有{}家待选店铺".format(len(gdf_within)))
275
+ if len(gdf_within) == 0:
276
+ final_out="None"
277
+ messagebox="sorry~这附近好像没有可以觅食的地方哦,换个地方试试吧"
278
+ else:
279
+ output_name_list = list(gdf_within['name'])
280
+ final_one = random.choice(output_name_list)
281
+ row_address = gdf_within[gdf_within['name']==final_one]
282
+ final_address = row_address['address'].values[0]
283
+ row_rating = gdf_within[gdf_within['name']==final_one]
284
+ final_rating = row_rating['overall_rating'].values[0]
285
+ row_label = gdf_within[gdf_within['name']==final_one]
286
+ final_label = row_label['label'].values[0]
287
+ row_price = gdf_within[gdf_within['name']==final_one]
288
+ final_price = row_label['price'].values[0]
289
+ row_hours = gdf_within[gdf_within['name']==final_one]
290
+ final_hours = row_label['shop_hours'].values[0]
291
+
292
+ final_out="今天去吃 【{}】 ,位置在 【{}】\n 【其他相关信息】:{} {} {}".format(final_one,final_address,final_rating,final_label,final_hours)
293
+ messagebox="运算正常"
294
+ return [final_out,run_count1,messagebox]
295
+
296
+ def POI_distribution(location1,location2,categories):
297
+
298
+ global run_count2
299
+ run_count2 += 1
300
+
301
+ min_long=float(location1.split(",")[0])
302
+ min_lat=float(location1.split(",")[1])
303
+ max_long=float(location2.split(",")[0])
304
+ max_lat=float(location2.split(",")[1])
305
+ long_bounds=max_long-min_long
306
+ lat_bounds=max_lat-min_lat
307
+ coords_lat_average=(min_lat+max_lat)/2
308
+ coords_delta_x=111*1000*0.01*math.cos(math.radians(coords_lat_average))
309
+ long_meterdif=long_bounds*coords_delta_x/0.01
310
+ lat_meterdif=lat_bounds/111*1000
311
+
312
+ print(long_meterdif)
313
+ print(lat_meterdif)
314
+
315
+ if lat_meterdif <3000 and long_meterdif <3000:
316
+
317
+ location=[location1,location2]
318
+ gdf_output=POI_baidu_distribution.POI_get(location,categories)
319
+
320
+ if len(gdf_output)==0:
321
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
322
+ ax = blankfig.add_subplot(111)
323
+ now = datetime.now()
324
+ timestamp = now.strftime("%Y%m%d%H%M%S")
325
+ poi_file_name = f"savepoi_{timestamp}.jpg"
326
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
327
+ svg_poiname=f"savepoi_{timestamp}.svg"
328
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
329
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
330
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
331
+ message_box="区域内没有该类型POI点"
332
+ return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
333
+ else:
334
+ message_box="POI获取正常"
335
+ matplotlib.rc("font",family='DengXian')
336
+ fig = plt.figure(figsize=(14,10),dpi = 100)
337
+ ax = fig.add_subplot(111)
338
+ wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
339
+ wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
340
+ scale_factor = 3
341
+ rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
342
+ wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
343
+ wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
344
+ wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
345
+
346
+ bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
347
+ difference_x = bounds[2] - bounds[0]
348
+ difference_y = bounds[3] - bounds[1]
349
+ target_scale=29.7/21
350
+ recent_scale=difference_x/difference_y
351
+ print(recent_scale)
352
+ if recent_scale>target_scale:
353
+ target_Dy=difference_x*21/29.7
354
+ bounds[3]=bounds[3]+(target_Dy-difference_y)/2
355
+ bounds[1]=bounds[1]-(target_Dy-difference_y)/2
356
+ elif recent_scale<target_scale:
357
+ target_Dx=difference_y*29.7/21
358
+ bounds[2]=bounds[2]+(target_Dx-difference_x)/2
359
+ bounds[0]=bounds[0]-(target_Dx-difference_x)/2
360
+ else:
361
+ pass
362
+ new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
363
+
364
+ ax.set_xlim(new_bounds[0],new_bounds[2])
365
+ ax.set_ylim(new_bounds[1],new_bounds[3])
366
+
367
+ new_dif_x=new_bounds[2]-new_bounds[0]
368
+ new_dif_y=new_bounds[3]-new_bounds[1]
369
+ unit_x=new_dif_x/14
370
+ unit_y=new_dif_y/10
371
+ list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
372
+ list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
373
+ plt.xticks(list_new_x)
374
+ plt.yticks(list_new_y)
375
+ plt.grid(True,zorder=1,alpha=0.5)
376
+ plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
377
+
378
+ grouped = gdf_output.groupby('category_us')
379
+ for group_name, group_data in grouped:
380
+ ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
381
+
382
+ rec_xy=(wgsmin_long,wgsmin_lat)
383
+ rec_width=wgsmax_long-wgsmin_long
384
+ rec_height=wgsmax_lat- wgsmin_lat
385
+ seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
386
+ ax.add_patch(seclected_area)
387
+
388
+ radius_circle=unit_x/4
389
+ layer_num=2
390
+ centroid_x=new_bounds[0]+unit_x
391
+ centroid_y=new_bounds[1]+unit_y
392
+ centroid_forcircle=(centroid_x,centroid_y)
393
+ circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
394
+ ax.add_patch(circle)
395
+ x_dataforline=[centroid_x,centroid_x]
396
+ y_dataforline=[centroid_y,centroid_y+radius_circle]
397
+ line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
398
+
399
+ x_datafortext=centroid_x
400
+ y_datafortext=centroid_y+radius_circle
401
+ ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
402
+
403
+ lat_average=(new_bounds[1]+new_bounds[3])/2
404
+ bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
405
+ text_y=bar_startpt[1]+radius_circle
406
+ teztsize=10
407
+ layer_num=2
408
+
409
+
410
+ delta_x=111*1000*0.01*math.cos(math.radians(lat_average))
411
+
412
+ unit_distance=unit_x*delta_x/0.01
413
+ if unit_distance/2>100:
414
+ nereast_num=int(unit_distance/100)*100
415
+ lon_randon=unit_x*nereast_num/unit_distance
416
+
417
+ barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
418
+ barran_ypt=(bar_startpt[1],bar_startpt[1])
419
+ barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
420
+
421
+ barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
422
+ barran3_ypt=(bar_startpt[1],bar_startpt[1])
423
+ barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
424
+
425
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
426
+ ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
427
+ ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
428
+ else:
429
+
430
+ num=100
431
+ lon100=unit_x*num/unit_distance
432
+ bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
433
+ bar100_ypt=(bar_startpt[1],bar_startpt[1])
434
+ bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
435
+ bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
436
+ bar300_ypt=(bar_startpt[1],bar_startpt[1])
437
+ bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
438
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
439
+ ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
440
+ ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
441
+ ax.legend(title='category_english', loc='upper right')
442
+
443
+ now = datetime.now()
444
+ timestamp = now.strftime("%Y%m%d%H%M%S")
445
+ poi_file_name = f"savepoi_{timestamp}.jpg"
446
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
447
+ svg_poiname=f"savepoi_{timestamp}.svg"
448
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
449
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
450
+ svgpoifile=fig.savefig(svg_poipath, format='svg', transparent=True)
451
+ return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
452
+
453
+ else:
454
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
455
+ ax = blankfig.add_subplot(111)
456
+ now = datetime.now()
457
+ timestamp = now.strftime("%Y%m%d%H%M%S")
458
+ poi_file_name = f"savepoi_{timestamp}.jpg"
459
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
460
+ svg_poiname=f"savepoi_{timestamp}.svg"
461
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
462
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
463
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
464
+ message_box="None"
465
+
466
+ return [poi_file_name,svg_poiname,run_count2,"区域过大,超过3KM限制",message_box]
467
+
468
+ def POI_kernel(location1,location2,category):
469
+
470
+ global run_count3
471
+ run_count3 += 1
472
+ min_long=float(location1.split(",")[0])
473
+ min_lat=float(location1.split(",")[1])
474
+ max_long=float(location2.split(",")[0])
475
+ max_lat=float(location2.split(",")[1])
476
+ long_bounds=max_long-min_long
477
+ lat_bounds=max_lat-min_lat
478
+ coords_lat_average=(min_lat+max_lat)/2
479
+ coords_delta_x=111*1000*0.01*math.cos(math.radians(coords_lat_average))
480
+ long_meterdif=long_bounds*coords_delta_x/0.01
481
+ lat_meterdif=lat_bounds/111*1000
482
+
483
+ print(long_meterdif)
484
+ print(lat_meterdif)
485
+
486
+ if lat_meterdif <3000 and long_meterdif <3000:
487
+
488
+ categories=[category]
489
+ location=[location1,location2]
490
+ gdf_output=POI_baidu_distribution.POI_get(location,categories)#获得所有的点
491
+ if len(gdf_output)==0:
492
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
493
+ ax = blankfig.add_subplot(111)
494
+ now = datetime.now()
495
+ timestamp = now.strftime("%Y%m%d%H%M%S")
496
+ poi_file_name = f"savepoi_{timestamp}.jpg"
497
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
498
+ svg_poiname=f"savepoi_{timestamp}.svg"
499
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
500
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
501
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
502
+ message_box="区域内没有该类型POI点"
503
+ return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
504
+ else:
505
+ message_box="POI获取正常"
506
+
507
+ matplotlib.rc("font",family='DengXian')
508
+
509
+ fig = plt.figure(figsize=(14,10),dpi = 100)
510
+ ax = fig.add_subplot(111)
511
+
512
+ wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
513
+ wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
514
+ scale_factor = 3
515
+ rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
516
+ wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
517
+ wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
518
+ wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
519
+
520
+ bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
521
+
522
+ difference_x = bounds[2] - bounds[0]
523
+ difference_y = bounds[3] - bounds[1]
524
+ target_scale=29.7/21
525
+ recent_scale=difference_x/difference_y
526
+ print(recent_scale)
527
+ if recent_scale>target_scale:
528
+ target_Dy=difference_x*21/29.7
529
+ bounds[3]=bounds[3]+(target_Dy-difference_y)/2
530
+ bounds[1]=bounds[1]-(target_Dy-difference_y)/2
531
+ elif recent_scale<target_scale:
532
+ target_Dx=difference_y*29.7/21
533
+ bounds[2]=bounds[2]+(target_Dx-difference_x)/2
534
+ bounds[0]=bounds[0]-(target_Dx-difference_x)/2
535
+ else:
536
+ pass
537
+ new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
538
+
539
+ ax.set_xlim(new_bounds[0],new_bounds[2])
540
+ ax.set_ylim(new_bounds[1],new_bounds[3])
541
+
542
+
543
+ new_dif_x=new_bounds[2]-new_bounds[0]
544
+ new_dif_y=new_bounds[3]-new_bounds[1]
545
+ unit_x=new_dif_x/14
546
+ unit_y=new_dif_y/10
547
+ list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
548
+ list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
549
+ plt.xticks(list_new_x)
550
+ plt.yticks(list_new_y)
551
+
552
+ plt.grid(True,zorder=1,alpha=0.5)
553
+
554
+ plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
555
+
556
+
557
+ grouped = gdf_output.groupby('category_us')
558
+ for group_name, group_data in grouped:
559
+ ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
560
+
561
+ sns.kdeplot(gdf_output,x="lng_wgs84",y="lat_wgs84",fill=True,alpha=.5,hue='category_us',legend=False,color="grey")
562
+
563
+ radius_circle=unit_x/4
564
+ layer_num=2
565
+ centroid_x=new_bounds[0]+unit_x
566
+ centroid_y=new_bounds[1]+unit_y
567
+ centroid_forcircle=(centroid_x,centroid_y)
568
+ circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
569
+ ax.add_patch(circle)
570
+ x_dataforline=[centroid_x,centroid_x]
571
+ y_dataforline=[centroid_y,centroid_y+radius_circle]
572
+ line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
573
+
574
+ x_datafortext=centroid_x
575
+ y_datafortext=centroid_y+radius_circle
576
+ ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
577
+
578
+ lat_average=(new_bounds[1]+new_bounds[3])/2
579
+ bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
580
+ text_y=bar_startpt[1]+radius_circle
581
+ teztsize=10
582
+ layer_num=2
583
+
584
+ delta_x=111*1000*0.01*math.cos(math.radians(lat_average))
585
+ unit_distance=unit_x*delta_x/0.01
586
+ if unit_distance/2>100:
587
+ nereast_num=int(unit_distance/100)*100
588
+ lon_randon=unit_x*nereast_num/unit_distance
589
+ barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
590
+ barran_ypt=(bar_startpt[1],bar_startpt[1])
591
+ barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
592
+ barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
593
+ barran3_ypt=(bar_startpt[1],bar_startpt[1])
594
+ barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
595
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
596
+ ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
597
+ ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
598
+ else:
599
+ num=100
600
+ lon100=unit_x*num/unit_distance
601
+ bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
602
+ bar100_ypt=(bar_startpt[1],bar_startpt[1])
603
+ bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
604
+ bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
605
+ bar300_ypt=(bar_startpt[1],bar_startpt[1])
606
+ bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
607
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
608
+ ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
609
+ ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
610
+ ax.legend(title='category_english')
611
+
612
+ now = datetime.now()
613
+ timestamp = now.strftime("%Y%m%d%H%M%S")
614
+ poiker_file_name = f"savepoiker_{timestamp}.jpg"
615
+ poiker_file_path = os.path.join(os.getcwd(), poiker_file_name)
616
+ svgker_name=f"savepoiker_{timestamp}.svg"
617
+ svgker_path=os.path.join(os.getcwd(),svgker_name)
618
+ poi_ker_file= plt.savefig(poiker_file_path, dpi=300)
619
+ svgkerfile=fig.savefig(svgker_path, format='svg', transparent=True)
620
+ print(f"文件保存路径:{poiker_file_path}")
621
+ return [poiker_file_name,svgker_name,run_count3,'区域选择符合限制', message_box]
622
+
623
+ else:
624
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
625
+ ax = blankfig.add_subplot(111)
626
+ now = datetime.now()
627
+ timestamp = now.strftime("%Y%m%d%H%M%S")
628
+ poi_file_name = f"savepoi_{timestamp}.jpg"
629
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
630
+ svg_poiname=f"savepoi_{timestamp}.svg"
631
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
632
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
633
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
634
+ message_box="None"
635
+
636
+ return [poi_file_name,svg_poiname,run_count3,"区域过大,超过3KM限制",message_box]
637
+
638
+
639
+ with gr.Blocks() as demo:
640
+ gr.Markdown(
641
+ """
642
+ # UrbanFlow-DataAnalysis
643
+ 使用说明和更多关于UrbanFlow的详情请查看链接:[UrbanFlow-DataAnalysis使用说明](https://gdz6btft72.feishu.cn/docx/E0pxd8pXpo4wOQxZ8eic7iSqnXc)
644
+ 如果您遇到排队较长或出图缓慢的情况,可以使用下列备用连接:[备用链接1](https://hf-mirror.com/spaces/onefan/UrbanFlow-DataAnalysis-Public) [备用链接2](https://hf-mirror.com/spaces/Mammmmmm/UrbanFlow-DataAnalysis-Public) [备用链接3](https://hf-mirror.com/spaces/Aryayaya/UrbanFlow-DataAnalysis-Public)
645
+ """
646
+ )
647
+ with gr.Tab("等时圈分析"):
648
+ with gr.Row():
649
+ with gr.Column():
650
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取坐标点,并输入最多六个角点坐标来对您想生成等时圈的区域进行控制")
651
+ with gr.Row():
652
+ co_input = [gr.Textbox(label=f"坐标角点参数 {i}", placeholder=f"请输入参数 {i}") for i in range(1, 7)]
653
+ drop1 = gr.CheckboxGroup(["walking","cycling","driving"], label="选择出行方式")
654
+ #box2=gr.Textbox()
655
+ drop2 = gr.CheckboxGroup(["5","10","15","20","25","30"], label="选择时间(min)")
656
+ report=gr.Textbox(label="报错提醒")
657
+ with gr.Column():
658
+ output_img = gr.Image()
659
+ output_svgpath = gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
660
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
661
+ cal_btn = gr.Button("Calculate")
662
+ # sav_svg = gr.DownloadButton("Save as SVG")
663
+ cal_btn.click(fn=isochrone, inputs=[drop2]+[drop1]+co_input, outputs=[output_img,output_svgpath,output_count,report])
664
+ # sav_svg.click(fn=isochrone,inputs=[drop2]+[drop1]+co_input,outputs=[output_svgpath])
665
+
666
+ gr.Markdown("""
667
+ ## 输入参数示例
668
+ """)
669
+ examples_index=[[["5"],["walking"],"113.924838,22.492807","","","",""],[["5"],["walking","cycling"],"113.923916,22.493438","113.924122,22.492887","113.924383,22.492348","113.924621,22.491827",""],[["5","10"],["walking"],"113.92366,22.493743","113.922101,22.494373","113.922159,22.494469","113.922272,22.494665","113.92242,22.494982"]]
670
+ gr.Examples(examples=examples_index,inputs=[drop2]+[drop1]+co_input,outputs=output_img,fn=isochrone,label="examples")
671
+
672
+ with gr.Tab("POI分布图"):
673
+ with gr.Row():
674
+ with gr.Column():
675
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
676
+ with gr.Row():
677
+ POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
678
+ gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
679
+ ]
680
+ with gr.Row():
681
+ POI_input2=gr.CheckboxGroup(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
682
+ with gr.Row():
683
+ with gr.Column():
684
+ report=gr.Textbox(label="区域限制报错提醒")
685
+ report2=gr.Textbox(label="POI数据获取报错提醒")
686
+
687
+ with gr.Column():
688
+ POI_output1=gr.Image(label="POI分布图")
689
+ POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
690
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
691
+
692
+ cal_btn = gr.Button("Calculate")
693
+ cal_btn.click(fn=POI_distribution, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
694
+ gr.Markdown("""
695
+ ## 输入参数示例
696
+ """)
697
+ examples_index=[["113.923428,22.491367","113.930983,22.495825",['商业服务设施-娱乐康体','公共服务设施-学校']],["113.930938,22.522402","113.942185,22.531515",['公共服务设施-学校','商业服务设施-餐饮']]]
698
+ gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_distribution,label="examples")
699
+
700
+
701
+ with gr.Tab("POI密度图"):
702
+ with gr.Row():
703
+ with gr.Column():
704
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
705
+ with gr.Row():
706
+ POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
707
+ gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
708
+ ]
709
+ POI_input2=gr.Radio(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
710
+ with gr.Row():
711
+ with gr.Column():
712
+ report=gr.Textbox(label="区域限制报错提醒")
713
+ report2=gr.Textbox(label="POI数据获取报错提醒")
714
+
715
+ with gr.Column():
716
+ POI_output1=gr.Image(label="POI密度图")
717
+ POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
718
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
719
+
720
+ cal_btn = gr.Button("Calculate")
721
+ cal_btn.click(fn=POI_kernel, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
722
+ gr.Markdown("""
723
+ ## 输入参数示例
724
+ """)
725
+ examples_index=[["113.923428,22.491367","113.930983,22.495825",'商业服务设施-娱乐康体'],["113.930938,22.522402","113.942185,22.531515",'商业服务设施-餐饮']]
726
+ gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_kernel,label="examples")
727
+
728
+
729
+ with gr.Tab("今天吃什么"):
730
+ with gr.Row():
731
+ with gr.Column():
732
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
733
+ foodlist_input1 = gr.Textbox(label="您所在位置的坐标点",placeholder="输入您所在位置的坐标点")
734
+ foodlist_input2=gr.Radio(["正餐","下午茶"],label="餐食类型")
735
+ foodlist_input3=gr.Slider(label="您愿意步行的距离(min)",minimum=0, maximum=10, step=1)
736
+ foodlist_btn=gr.Button("开始丢骰子")
737
+ foodlist_output=gr.Textbox(label="今天吃什么",lines=5)
738
+ with gr.Row():
739
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
740
+ textbox=gr.Textbox(label="报错提醒")
741
+ foodlist_btn.click(fn=random_foodchoice,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=[foodlist_output,output_count,textbox])
742
+ gr.Markdown("""
743
+ ## 输入参数示例
744
+ """)
745
+ examples_index=[["113.924838,22.492807","正餐","10"],["113.924838,22.492807","下午茶","5"]]
746
+ gr.Examples(examples=examples_index,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=foodlist_output,fn=random_foodchoice,label="examples")
747
+
748
+
749
+ demo.launch(share=True)
750
+