Question
I am using the google maps api to get the distance between two cities. My api call returns the data in json but I am
I am using the google maps api to get the distance between two cities. My api call returns the data in json but I am having troble extracting the data. I need to get he distqance. I thought this would work:
result= simplejson.load(x) dist = result['rows'][0]['elements'][0]['distance'][0]['text']
But I get an error:
________________________________________-
Exception in Tkinter callback Traceback (most recent call last): File "C:\Python\lib\tkinter\__init__.py", line 1702, in __call__ return self.func(*args) File "C:\Users\Kristen Albrecht\OneDrive\Joint Documents\Education\UCLA Applications Programing\Python\Week 7\KristenAlbrechtFinalProject\main.py", line 41, in
____________________________________
Here is my code:
______________________________
from tkinter import * import json import requests import simplejson import urllib
class Distance: def __init__(self, master): self.master = master master.title("D") class Tour: def __init__(self, master): self.master = master master.title("Tour") Label(master, text="Orgin").grid(row=0, column=0) Label(master, text="Destination").grid(row=2, column=0) Label(master, text="Mode").grid(row=4, column=0) Label(master, text="Distance").grid(row=6, column=0) e1 = Entry(master) e2 = Entry(master) e3 = Entry(master) e4 = Entry(master) e1.grid(row=1, column=0, padx=10, pady=10) e2.grid(row=3, column=0, padx=10, pady=10) e3.grid(row=5, column=0, padx=10, pady=10) e4.grid(row=7, column=0, padx=10, pady=10) Button(master, text='GetDistance', command= lambda: self.onClick(e1, e2, e3, e4)).grid(row=8, column=0, sticky=W, pady=4) def onClick(self, e1, e2, e3, e4): #api_key = 'AIzaSyCTzy54Y4XxqFuxNPKVxvpnJO5iNpdofOI'
source = e1.get() dest = e2.get() mode = e3.get() url ='https://maps.googleapis.com/maps/api/distancematrix/json?' r = requests.get('http://maps.googleapis.com/maps/api/distancematrix/json?origins=New+York+NY&destinations=Lansing+MI&mode=driving&sensor=false') #r = requests.get(url + 'origins =' + source + '&destinations= ' + dest + '&mode=' + mode + '&sensor=false') #earlier code with spaces in the url # r = requests.get(url + 'origins=' + source + '&destinations=' + dest + '&mode=' + mode + '&sensor=false') #fixed with no spaces in the url x = r.json() print(x) result= simplejson.load(x) dist = result['rows'][0]['elements'][0]['distance'][0]['text'] print(driving_time) #e4.insert(0, dist)
root = Tk()
my_gui = Tour(root)
root.mainloop()
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started