準備工作

在開始之前,請確保您已設置好 Google Places API 并獲取了 API 密鑰。本文將使用 Place Search API 的“附近搜索”端點來實現功能。

環境準備

首先,創建一個新文件,例如 [rest](http://m.dlbhg.com/provider/uid2024123057893a6ee1f4)aurants.py,并導入以下所需的 Python 包:

import random
import geocoder
import requests
import json
import geopy.distance

# 獲取當前位置的經緯度
g = geocoder.ip('me')
currLocCoords = (g.latlng[0], g.latlng[1])
currLocCoordsURL = str(g.latlng[0]) + "%2C" + str(g.latlng[1])

# Google Places API 基礎 URL
my_api_key = "&key=YOUR_API_KEY"
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + currLocCoordsURL

如果您尚未安裝這些包,可以通過 pip install 命令安裝。


構建 API 請求 URL

為了找到附近的餐館,我們需要構建一個包含參數的 API 請求 URL。以下代碼展示了如何根據用戶輸入動態生成 URL:

# 獲取用戶輸入的餐廳類型
[keyword](http://m.dlbhg.com/provider/uid2024121921342cbdf802) = input("What type of restaurant? (optional) ").lower().replace(" ", "%20")
if keyword != "":
 keyword = "&keyword=" + keyword
else:
 keyword = "&keyword=[food](http://m.dlbhg.com/provider/uid2024102319521f45d719)"
url = url + keyword

# 獲取用戶輸入的價格范圍
maxprice = input("Maximum $s, 0 to 4? (optional) ")
if maxprice != "":
 maxprice = "&maxprice=" + maxprice
 url = url + maxprice

# 獲取用戶是否要求餐廳當前營業
opennow = input("Does it have to be open now? (Y or N, optional) ").lower()
if opennow == "y":
 opennow = "&opennow=true"
 url = url + opennow
elif opennow == "n":
 opennow = "&opennow=false"
 url = url + opennow

# 獲取用戶輸入的搜索半徑
radius = input("Maximum distance willing to go in miles? (optional) ")
if radius != "":
 radius = str(round(float(radius) * 1609.34)) 

# 轉換為米
 radius = "&radius=" + radius
 url = url + radius
else:
 url = url + "&radius=3200" 

# 默認半徑為3200米(約2英里)

通過以上代碼,用戶可以靈活設置搜索參數,包括餐廳類型、價格范圍、是否營業以及搜索半徑。


發送 API 請求并解析結果

完成 URL 構建后,我們將發送 HTTP 請求并解析返回的 JSON 數據:

# 添加 API 密鑰并發送請求
url = url + my_api_key
response = requests.request("GET", url)

# 解析 JSON 響應
response = json.loads(response.text)
status = response['status']
if status == "OK":
 results = response["results"]
else:
 print(status)
 exit()

status 字段用于檢查請求是否成功,例如返回 "OK" 表示成功,而 "ZERO_RESULTS" 表示沒有找到結果。


定義餐廳類

為了更方便地處理返回的餐廳數據,我們定義了一個 restaurant 類,用于存儲餐廳的關鍵信息:

class restaurant:
 def __init__(self):
 self.name = ""
 self.businessStatus = ""
 self.openNow = False
 self.priceLevel = ""
 self.rating = -1
 self.totalUserRatings = -1
 self.distance = -1
 self.address = ""

處理返回的餐廳數據

以下代碼通過循環處理返回的 JSON 數據,并提取關鍵信息存儲到 restaurant 對象中:

numPlaces = len(results)
restAttributesList = ["name", "businessStatus", "openNow", "priceLevel", "rating", "totalUserRatings", "distance", "address"]
restInstVarList = []

for i in range(numPlaces):
 currPlace = results[i]
 rest = restaurant()

 try:
 rest.name = currPlace["name"]
 except KeyError:
 pass

 try:
 rest.businessStatus = currPlace["business_status"]
 except KeyError:
 pass

 try:
 rest.openNow = currPlace["opening_hours"]["open_now"]
 except KeyError:
 pass

 try:
 rest.priceLevel = currPlace["price_level"]
 except KeyError:
 pass

 try:
 rest.rating = currPlace["rating"]
 except KeyError:
 pass

 try:
 rest.totalUserRatings = currPlace["user_ratings_total"]
 except KeyError:
 pass

 try:
 placeCoords = currPlace["geometry"]["location"]
 currPlaceCoords = (placeCoords["lat"], placeCoords["lng"])
 rest.distance = geopy.distance.geodesic(currLocCoords, currPlaceCoords).miles
 except KeyError:
 pass

 try:
 rest.address = currPlace["vicinity"]
 except KeyError:
 pass

 restInstVarList.append(vars(rest))

通過 try-except 塊,我們可以安全地處理缺失字段,避免程序因 KeyError 中斷。


輸出餐廳信息

以下代碼用于打印所有餐廳的信息:

for r in restInstVarList:
 print(r["name"] + ": ")
 for i in range(1, 8):
 a = restAttributesList[i]
 print("t" + a + ": " + str(r[a]))
 print("n")

如果希望隨機選擇一家餐廳,可以使用以下代碼:

import random

randomChoice = random.choice(restInstVarList)
print(randomChoice["name"] + ": ")
for i in range(1, 8):
 a = restAttributesList[i]
 print("t" + a + ": " + str(randomChoice[a]))

總結

通過本文的教程,您可以使用 Google Places API 構建一個簡單的餐廳選擇程序。這個項目不僅能解決實際問題,還能幫助您學習和實踐 API 調用、數據處理等編程技能。如果您有任何問題或建議,歡迎留言交流。


原文鏈接: https://medium.com/@nagasameer/building-a-restaurant-picker-program-using-google-places-api-99aa3108310

上一篇:

關于Facebook API Feed你需要知道的事

下一篇:

在線訂餐API集成
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費