如何在Django框架中利用Google Places API获取指定地点附近酒店?
基于Django集成Google Places API实现附近酒店搜索
1. 前期准备
- 登录Google Cloud控制台,创建项目并启用Places API和Geocoding API(前者用于搜索酒店,后者将用户输入的地点转换为经纬度),生成API密钥。
- 安装HTTP请求库:
pip install requests
2. Django项目配置
在settings.py中配置API密钥(建议用环境变量避免硬编码泄露):
# settings.py import os GOOGLE_PLACES_API_KEY = os.environ.get('GOOGLE_PLACES_API_KEY', '你的测试密钥')
3. 编写视图函数
在views.py中实现接收用户输入、调用API、处理返回数据的逻辑:
# views.py import requests from django.shortcuts import render from django.conf import settings def hotel_search(request): hotels = [] if request.method == 'POST': location = request.POST.get('location') # 1. 将地点转换为经纬度 geocode_url = f"https://maps.googleapis.com/maps/api/geocode/json?address={location}&key={settings.GOOGLE_PLACES_API_KEY}" geocode_res = requests.get(geocode_url).json() if geocode_res.get('status') == 'OK': lat = geocode_res['results'][0]['geometry']['location']['lat'] lng = geocode_res['results'][0]['geometry']['location']['lng'] # 2. 搜索附近酒店(半径5000米,类型为住宿) places_url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lng}&radius=5000&type=lodging&key={settings.GOOGLE_PLACES_API_KEY}" places_res = requests.get(places_url).json() if places_res.get('status') == 'OK': hotels = places_res['results'] return render(request, 'hotel_search.html', {'hotels': hotels})
4. 创建前端模板
在templates目录下新建hotel_search.html,实现输入表单和结果展示:
<!-- hotel_search.html --> <!DOCTYPE html> <html> <head> <title>附近酒店搜索</title> </head> <body> <h1>搜索附近酒店</h1> <form method="post"> {% csrf_token %} <input type="text" name="location" placeholder="输入地点(如:上海陆家嘴)" required> <button type="submit">搜索</button> </form> {% if hotels %} <h2>搜索结果</h2> <ul> {% for hotel in hotels %} <li> <h3>{{ hotel.name }}</h3> <p>地址:{{ hotel.vicinity }}</p> {% if hotel.rating %} <p>评分:{{ hotel.rating }}/5</p> {% endif %} </li> {% endfor %} </ul> {% endif %} </body> </html>
5. 配置URL路由
在项目根目录的urls.py中添加路由:
# urls.py from django.urls import path from . import views urlpatterns = [ path('hotels/', views.hotel_search, name='hotel_search'), ]
6. 关键注意事项
- 密钥安全:生产环境务必用环境变量存储密钥,并在Google Cloud控制台限制密钥的调用IP/域名,防止滥用。
- API配额:Google Places API有调用次数和费用限制,测试时注意查看控制台的使用情况,避免超额。
- 错误处理:实际项目中需处理API返回的异常状态(如
ZERO_RESULTS无结果、OVER_QUERY_LIMIT配额耗尽等),给用户友好提示。 - 分页扩展:默认返回20条结果,如需更多,可使用返回的
next_page_token发起后续请求获取分页数据。
内容的提问来源于stack exchange,提问作者vctr
相关产品推荐
相关产品推荐

