如何在Django中调用Google Geocoding实现邮编查附近餐厅功能
代码问题与优化点
- 你的表单是普通
Form类而非ModelForm,不存在save()方法,调用form.save(commit=False)会直接抛出异常,直接从cleaned_data里取邮编即可 - 变量名错误:解析后的API返回值存在
data变量中,后续取值却用了未定义的geodata,会触发NameError - Google Geocoding API的请求URL拼接错误:额外给地址加了单引号,且未对邮编做URL编码,会导致API返回无效请求错误
- 响应返回逻辑错误:Django普通视图不能直接用
Response(这是DRF的响应类),应该用render方法,且上下文传参格式不符合要求 - 异常处理缺失:没有判断Google API返回的
status是否为OK,也没有处理网络请求失败、无返回结果的边界情况 - 非GET请求的分支逻辑错误:
raise PropertyForm()完全不符合语法,应该实例化空表单传给模板渲染 - 缺少获取附近餐厅的逻辑:你只调用了Geocoding API转经纬度,还需要调用Google Places API传入经纬度获取附近餐厅数据传给模板
修正后的代码
views.py
import json import urllib.parse import urllib.request from django.shortcuts import render, Http404 from .forms import PropertyForm # 替换为你自己的Google API密钥 GOOGLE_API_KEY = "你的APIKEY" def property_add(request): form = PropertyForm(request.GET or None) context = { 'form': form, 'latlon': None, 'locations': [] } if form.is_valid(): # 直接从表单清洗数据里取邮编 postcode = form.cleaned_data['postcode'] # 正确拼接Geocoding API URL,做URL编码 address = urllib.parse.quote(f"{postcode} SG") geo_url = f'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={GOOGLE_API_KEY}' try: # 发送请求解析响应 res = urllib.request.urlopen(geo_url, timeout=10).read() geo_data = json.loads(res) if geo_data['status'] != 'OK' or not geo_data.get('results'): raise ValueError("无效邮编,无法获取经纬度") # 提取经纬度 lat = geo_data['results'][0]['geometry']['location']['lat'] lon = geo_data['results'][0]['geometry']['location']['lng'] context['latlon'] = f"纬度:{lat}, 经度:{lon}" # 调用Places API获取附近餐厅,半径可自行调整,单位米 place_url = f'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lon}&radius=2000&type=restaurant&key={GOOGLE_API_KEY}' place_res = urllib.request.urlopen(place_url, timeout=10).read() place_data = json.loads(place_res) if place_data['status'] == 'OK': context['locations'] = place_data['results'] except Exception as e: # 可根据需要添加错误提示 context['error'] = str(e) # 渲染模板 return render(request, 'food/location_index.html', context)
forms.py 无需修改
模板调整(food/location_index.html)
把餐厅遍历部分调整为适配Places API返回的字段:
{% extends 'base.html' %} {% load static %} {% block content %} <h2>Food places!!!</h2> <hr> {% if error %} <p style="color:red;">错误:{{ error }}</p> {% endif %} {% for location in locations %} <h2>{{ location.name }}</h2> <p>地址:{{ location.vicinity }}</p> {% empty %} <p>暂无附近餐厅数据</p> {% endfor %} <form action='' method="get"> {{ form }} <input type="submit" value="Submit"> </form> {% if latlon %} <p>Your current location is {{ latlon }} </p> {% endif %} {% endblock content %}
urls.py配置
在你的app的urls.py中添加对应路由即可,示例:
from django.urls import path from . import views urlpatterns = [ path('search-restaurant/', views.property_add, name='search_restaurant'), ]
如果需要全局访问,记得在项目根urls.py中引入该app的路由配置。
内容的提问来源于stack exchange,提问作者rocket8900
相关产品推荐
相关产品推荐

