Hi, today I want to share with this awesome community how I did to get the distance between two coordinates that can be from a map, from a database or written by hand.
First of all remember that if you are going to use it for a web app with a lot of traffic, Google is going to charge you a fee that can be little or a lot depending on the traffic, you can check the prices here: https://developers.google.com/ maps / billing / gmp-billing # dynamic-maps
Ok in just 3 steps you will have this working.
First step: get a google key for developers here: https://developers.google.com/maps/documentation/javascript/get-api-key
Second Step: In my example I just want to know the distance between a moving point to a point that is always fixed, but you can also do it to a point that is also a variable.
That’s why I’m only going to use 2 variables: latitude and longitude and two constants that will also have latitude and longitude.
You can get this data in many ways, I did it by creating a google map component :
So u have now a latitude and a longitude:
maps1.latitude
maps1.longitude
Third step: on the client side, open the components panel in DATA, choose the “Api Action” component
In our new api action we can change the id in this case I put api4, in method we leave GET, set No Auto Load
and update only on specific events, otherwise costs can go up very fast, in data type we select JSON and we do not write any URL, but we go to Dynamic Attributes, we select URL and copy and paste this code :
https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=’+maps1.latitude+’,’+maps1.longitude+’&destinations=-34.603103%2C-58.391606&key=write here your key
Obviously in “write here your key” you have to write your own key that you got it in step 1.
Here is the entire code of my api action:
<dmx-api-action id="api4" data-type="json"
dmx-bind:url="'https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins='+maps1.latitude+','+maps1.longitude+'&destinations=-34.603103%2C-58.391606&key=*Your Api Key*'" noload>
</dmx-api-action>
Ok now you have everything ready but how do you see the distance or the duration?
Very easy, you can create a title or a paragraph on your page and create a bind like this:
Here is the code of the bind for Time and Distance:
api4.data.rows[0].elements[0].duration.text+' '+api4.data.rows[0].elements[0].distance.text
As you can see, this method is really easy and fast, you can use it in many ways, here you can see the documentation with which you can add or change parameters such as the metric system for example so that instead of kilometers you can use miles and much more.
I hope you find it useful.
Cheers