Spaces:
Running
Running
Commit
·
8260f15
1
Parent(s):
fd32f16
改用google map 地址轉換
Browse files
app.py
CHANGED
@@ -80,28 +80,32 @@ def find_nearest_store(address, lat, lon, distance_km):
|
|
80 |
"""
|
81 |
print(f"🔍 收到查詢請求: address={address}, lat={lat}, lon={lon}, distance_km={distance_km}")
|
82 |
|
83 |
-
# 若有填地址但 lat/lon 為 0
|
84 |
if address and address.strip() != "" and (lat == 0 or lon == 0):
|
85 |
try:
|
86 |
import requests
|
87 |
-
|
|
|
|
|
|
|
|
|
88 |
params = {
|
89 |
-
"
|
90 |
-
"
|
91 |
-
"limit": 1,
|
92 |
-
"countrycodes": "tw"
|
93 |
}
|
94 |
-
resp = requests.get(geocode_url, params=params
|
95 |
resp.raise_for_status()
|
96 |
data = resp.json()
|
97 |
-
if data:
|
98 |
-
|
99 |
-
|
|
|
100 |
print(f"地址轉換成功: {address} => lat={lat}, lon={lon}")
|
101 |
else:
|
|
|
102 |
return [["❌ 地址轉換失敗,請輸入正確地址", "", "", "", ""]], 0, 0
|
103 |
except Exception as e:
|
104 |
-
print(f"❌
|
105 |
return [["❌ 地址轉換失敗,請輸入正確地址", "", "", "", ""]], 0, 0
|
106 |
|
107 |
if lat == 0 or lon == 0:
|
|
|
80 |
"""
|
81 |
print(f"🔍 收到查詢請求: address={address}, lat={lat}, lon={lon}, distance_km={distance_km}")
|
82 |
|
83 |
+
# 若有填地址但 lat/lon 為 0,嘗試用 Google Geocoding API
|
84 |
if address and address.strip() != "" and (lat == 0 or lon == 0):
|
85 |
try:
|
86 |
import requests
|
87 |
+
import os
|
88 |
+
googlekey = os.environ.get("googlekey")
|
89 |
+
if not googlekey:
|
90 |
+
raise RuntimeError("未設定 googlekey,請於 Huggingface Space Secrets 設定。")
|
91 |
+
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json"
|
92 |
params = {
|
93 |
+
"address": address,
|
94 |
+
"key": googlekey
|
|
|
|
|
95 |
}
|
96 |
+
resp = requests.get(geocode_url, params=params)
|
97 |
resp.raise_for_status()
|
98 |
data = resp.json()
|
99 |
+
if data.get("status") == "OK" and data.get("results"):
|
100 |
+
location = data["results"][0]["geometry"]["location"]
|
101 |
+
lat = float(location["lat"])
|
102 |
+
lon = float(location["lng"])
|
103 |
print(f"地址轉換成功: {address} => lat={lat}, lon={lon}")
|
104 |
else:
|
105 |
+
print(f"❌ Google Geocoding 失敗: {data}")
|
106 |
return [["❌ 地址轉換失敗,請輸入正確地址", "", "", "", ""]], 0, 0
|
107 |
except Exception as e:
|
108 |
+
print(f"❌ Google Geocoding 失敗: {e}")
|
109 |
return [["❌ 地址轉換失敗,請輸入正確地址", "", "", "", ""]], 0, 0
|
110 |
|
111 |
if lat == 0 or lon == 0:
|