準(zhǔn)備工作

在開(kāi)始之前,請(qǐng)確保您已設(shè)置好 Google Places API 并獲取了 API 密鑰。本文將使用 Place Search API 的“附近搜索”端點(diǎn)來(lái)實(shí)現(xiàn)功能。

環(huán)境準(zhǔn)備

首先,創(chuàng)建一個(gè)新文件,例如 [rest](http://www.dlbhg.com/provider/uid2024123057893a6ee1f4)aurants.py,并導(dǎo)入以下所需的 Python 包:

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

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

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

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


構(gòu)建 API 請(qǐng)求 URL

為了找到附近的餐館,我們需要構(gòu)建一個(gè)包含參數(shù)的 API 請(qǐng)求 URL。以下代碼展示了如何根據(jù)用戶(hù)輸入動(dòng)態(tài)生成 URL:

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

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

# 獲取用戶(hù)是否要求餐廳當(dāng)前營(yíng)業(yè)
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

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

# 轉(zhuǎn)換為米
 radius = "&radius=" + radius
 url = url + radius
else:
 url = url + "&radius=3200" 

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

通過(guò)以上代碼,用戶(hù)可以靈活設(shè)置搜索參數(shù),包括餐廳類(lèi)型、價(jià)格范圍、是否營(yíng)業(yè)以及搜索半徑。


發(fā)送 API 請(qǐng)求并解析結(jié)果

完成 URL 構(gòu)建后,我們將發(fā)送 HTTP 請(qǐng)求并解析返回的 JSON 數(shù)據(jù):

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

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

status 字段用于檢查請(qǐng)求是否成功,例如返回 "OK" 表示成功,而 "ZERO_RESULTS" 表示沒(méi)有找到結(jié)果。


定義餐廳類(lèi)

為了更方便地處理返回的餐廳數(shù)據(jù),我們定義了一個(gè) restaurant 類(lèi),用于存儲(chǔ)餐廳的關(guān)鍵信息:

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 = ""

處理返回的餐廳數(shù)據(jù)

以下代碼通過(guò)循環(huán)處理返回的 JSON 數(shù)據(jù),并提取關(guān)鍵信息存儲(chǔ)到 restaurant 對(duì)象中:

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))

通過(guò) 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")

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

import random

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

總結(jié)

通過(guò)本文的教程,您可以使用 Google Places API 構(gòu)建一個(gè)簡(jiǎn)單的餐廳選擇程序。這個(gè)項(xiàng)目不僅能解決實(shí)際問(wèn)題,還能幫助您學(xué)習(xí)和實(shí)踐 API 調(diào)用、數(shù)據(jù)處理等編程技能。如果您有任何問(wèn)題或建議,歡迎留言交流。


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

上一篇:

關(guān)于Facebook API Feed你需要知道的事

下一篇:

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

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)