所有文章 > 如何集成API > 使用 Google Places API 构建餐厅选择程序
使用 Google Places API 构建餐厅选择程序

使用 Google Places API 构建餐厅选择程序

在日常生活中,选择餐厅可能是一个让人头疼的问题。无论是与朋友还是伴侣,总是会陷入“去哪吃”的循环讨论中。为了简化这个过程,本文将介绍如何使用 Google Places API 构建一个餐厅选择程序,帮助快速决策。


准备工作

在开始之前,请确保您已设置好 Google Places API 并获取了 API 密钥。本文将使用 Place Search API 的“附近搜索”端点来实现功能。

环境准备

首先,创建一个新文件,例如 [rest](https://www.explinks.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](https://www.explinks.com/provider/uid2024121921342cbdf802) = input("What type of restaurant? (optional) ").lower().replace(" ", "%20")
if keyword != "":
 keyword = "&keyword=" + keyword
else:
 keyword = "&keyword=[food](https://www.explinks.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
#你可能也喜欢这些API文章!

我们有何不同?

API服务商零注册

多API并行试用

数据驱动选型,提升决策效率

查看全部API→
🔥

热门场景实测,选对API

#AI文本生成大模型API

对比大模型API的内容创意新颖性、情感共鸣力、商业转化潜力

25个渠道
一键对比试用API 限时免费

#AI深度推理大模型API

对比大模型API的逻辑推理准确性、分析深度、可视化建议合理性

10个渠道
一键对比试用API 限时免费