How do you calculate the driving distance between two locations or cities using Google Maps API?

Hello, MIT Community!

I am working on adding a new feature to my app that can calculate the distance (in km) between two locations (or cities) using Google Maps API.

Could someone advise and share insights on how to achieve this, please?

1 Like

Thank you, Steve for sharing the Google Distance Matrix API overview.

I was able to setup the API key and successfully get the response from Google about the distance between two locations.

The only pending thing is that I am getting an error when I try to extract the distanceText value from the nested field of the responseContent!

--

Enclosed are the blocks and the response error for more details. I appreciate it if someone could advise on what the wrong part is.

You did the JSONWebDecode operation last.

It has to be done first, against responseContent.
Also, I recommend using JSONWebDecodeWithDictionaries instead. It should give you a dictionary.

After that, add extra global variables to catch each result as you peel the dictionary one layer at a time, working outside in.

Your lookup keys, working outside in, are:
'rows'
1
'elements'
1
'distance'
'text'

This is a guess based on your error message.
Actual responseContent in text form would make it possible to test this guess.
blocks (1)

1 Like

Hello, ABG - I am considering the JSONWebDecodeWithDictionaries instead as it makes the code more effective and simpler.

The app is perfectly working now. Thank you so much for your time and support!

Please show us the code that worked, for closure and for the next guy?

-- Here are the final screen and blocks I used to calculate the driving distance and duration time between two locations or cities using Google Distance Matrix API.

1 Like

Here's another way of cleaning eggshells off a list result where you don't know your list length:
image

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.