onefan commited on
Commit
bb97e41
·
verified ·
1 Parent(s): 32b7433

Update app.py

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