首页 > 解决方案 > django python google距离矩阵api json问题

问题描述

所以,我是 python 和 Django 的新手。我为使用谷歌距离矩阵 api 的非常基本的表单创建了一个视图和 html 页面。我能够将 json 的输出显示回我的 html 页面,没有任何问题。问题是,我如何获得以英里为单位的距离以显示在我的 html 页面上。现在我只是得到原始的json。但我似乎无法获得以英里为单位的距离。

HTML 页面的当前输出:

    origin ['660 Celebration Ave, Celebration, FL 34747, USA']

    destination ['878 Columbus Ave, New York, NY 10023, USA']

    distance in miles: [{'elements': [{'distance': {'text': '1,093 mi', 'value': 1759428}, 
   'duration': {'text': '16 hours 13 mins', 'value': 58364}, 'status': 'OK'}]}]

''' 意见.py

def mapdistance_view(request):
distance = {}

if 'From' in request.GET:
    origin = request.GET['From']
    destination = request.GET['To']
    apikey = "mykey"
    url = 'https://maps.googleapis.com/maps/api/distancematrix/json?mode=driving&units=imperial&origins=' + origin + ',DC&destinations=' + destination + ',' + apikey      
    response = requests.get(url)
    distance = response.json()
    print(url)
    print(distance)
return render(request, 'mapdistance.html', {'distance': distance})

'''

html页面'''

   {% block content %}
   <h2>map API</h2>
    <form method="GET"> {% csrf_token %}
   <label>Pickup Location:</label><input type="text" name="From"><br>
   <label>Delivery Location:</label><input type="text" name="To"><br>
   <button type="submit">post to google map</button>
   </form>
   {% if distance %}
   <p><strong>origin {{ distance.origin_addresses }}</strong></p>
   <p><strong>destination {{ distance.destination_addresses }}</strong></p>
       <p><strong>distance in miles: {{ distance.rows }}</strong></p>
  {% endif %}
  {% endblock %}

'''

标签: pythondjangogoogle-maps-api-3

解决方案


我不确定如何在 Html 中索引 JSON,但你可以做这样的事情。首先,我在包含以英里为单位的距离的段落中添加了一个 ID。然后我导入 jquery 并将其嵌套到脚本标签中。在jquery中,选择id段落,将里面的内容改成json对象索引。

下面是它应该是什么样子的粗略概述,但它可能有用吗?Superrrrr hacky 方法来索引 json 对象,希望有一种更清洁的方法。

{% block content %}
<h2>map API</h2>
<form method="GET"> {% csrf_token %}
<label>Pickup Location:</label><input type="text" name="From"><br>
<label>Delivery Location:</label><input type="text" name="To"><br>
<button type="submit">post to google map</button>
</form>
{% if distance %}
<p><strong>origin {{ distance.origin_addresses }}</strong></p>
<p><strong>destination {{ distance.destination_addresses }}</strong></p>
   <p id="miles-paragraph"><strong>distance in miles: {{ distance.rows }}</strong></p>
{% endif %}
{% endblock %}

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256- WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script>
var value = JSON.parse("{{distance|escapejs}}");
$(document).ready(function(){
$('#miles-paragraph').html(value[0]["elements"]["distance"]["text"]);
</script>

推荐阅读