Roberta2024 commited on
Commit
e500adc
·
verified ·
1 Parent(s): 43a78ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -9
app.py CHANGED
@@ -7,7 +7,8 @@ import base64
7
  import folium
8
  from streamlit_folium import st_folium
9
  from geopy.geocoders import Nominatim
10
- from geopy.exc import GeocoderTimedOut
 
11
 
12
  # Function to set background image
13
  def set_background(png_file):
@@ -67,12 +68,21 @@ data_list = []
67
  # Initialize the geolocator
68
  geolocator = Nominatim(user_agent="geoapiExercises")
69
 
70
- # Function to geocode an address
71
- def geocode_address(address):
72
- try:
73
- return geolocator.geocode(address)
74
- except GeocoderTimedOut:
75
- return geocode_address(address)
 
 
 
 
 
 
 
 
 
76
 
77
  # Scrape data when the button is pressed
78
  if st.button('開始爬取資料'):
@@ -101,8 +111,6 @@ if st.button('開始爬取資料'):
101
  "經度": location.longitude,
102
  "緯度": location.latitude
103
  })
104
- else:
105
- st.warning(f"無法獲取經緯度: {address}")
106
 
107
  # If data was scraped successfully
108
  if data_list:
 
7
  import folium
8
  from streamlit_folium import st_folium
9
  from geopy.geocoders import Nominatim
10
+ from geopy.exc import GeocoderTimedOut, GeocoderServiceError
11
+ import time
12
 
13
  # Function to set background image
14
  def set_background(png_file):
 
68
  # Initialize the geolocator
69
  geolocator = Nominatim(user_agent="geoapiExercises")
70
 
71
+ # Function to geocode an address with retry logic
72
+ def geocode_address(address, retries=3, delay=2):
73
+ for i in range(retries):
74
+ try:
75
+ location = geolocator.geocode(address)
76
+ if location:
77
+ return location
78
+ except (GeocoderTimedOut, GeocoderServiceError) as e:
79
+ st.warning(f"Geocoding error: {e}. Retrying...")
80
+ time.sleep(delay)
81
+ except GeocoderServiceError as e:
82
+ st.error(f"Service error: {e}")
83
+ break
84
+ st.warning(f"Failed to geocode address: {address}")
85
+ return None
86
 
87
  # Scrape data when the button is pressed
88
  if st.button('開始爬取資料'):
 
111
  "經度": location.longitude,
112
  "緯度": location.latitude
113
  })
 
 
114
 
115
  # If data was scraped successfully
116
  if data_list: