I am trying to use the bing maps api to get travel time and distance between 2 gps coordinates. I get a json answer, however, I am not able to get the values out of this dictionary ?
import requests
import json
payload = {
"origins": [{"latitude": 50.781869, "longitude": 4.596188}],
"destinations": [{"latitude": 50.87650130092019, "longitude": 4.671327819416231}],
"travelMode": "driving",
}
paramtr = {"key": "mybingAPIkey"}
r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = json.dumps(payload), params = paramtr)
print(r.json())
gives the following result:
{
'authenticationResultCode': 'ValidCredentials',
'brandLogoUri': 'http: //dev.virtualearth.net/Branding/logo_powered_by.png',
'copyright': 'Copyright © 2023 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.',
'resourceSets': [
{
'estimatedTotal': 1,
'resources': [
{
'__type': 'DistanceMatrix:http://schemas.microsoft.com/search/local/ws/rest/v1',
'destinations': [
{
'latitude': 50.87650130092019,
'longitude': 4.671327819416231
}
],
'origins': [
{
'latitude': 50.781869,
'longitude': 4.596188
}
],
'results': [
{
'destinationIndex': 0,
'originIndex': 0,
'totalWalkDuration': 0,
'travelDistance': 14.511,
'travelDuration': 21.9667
}
]
}
]
}
],
'statusCode': 200,
'statusDescription': 'OK',
'traceId': '7fecad5b38b94df9acef6287488b68c9|DU0000273D|0.0.0.0|DU000005E8'
}
now: how do I get the travelDistance out of this ? (14.511 in this case) or the travelDuration ? (21.9667)
tried to get the key and value pairs, but not really getting further with this.
with some other code, I got the keys :
authenticationResultCode brandLogoUri copyright resourceSets statusCode statusDescription traceId
CodePudding user response:
You could also use json.loads()
and pass the content of your response. Then access values like you do from a dictionary:
r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = json.dumps(payload), params = paramtr)
dt = json.loads(r.content)
travelDistance = dt['resourceSets'][0]['resources'][0]['results'][0]['travelDistance']
travelDuration = dt['resourceSets'][0]['resources'][0]['results'][0]['travelDuration']