In my blog post “https://rutg3r.com/gps-data-traccar-homeseer/” a calculation was made in script line 139 to calculate the distance between 2 locations. Because this is an aerial measurement, it’s not quite accurate. For defining a geofence it’s fine, but to have a more accurate travel duration and distance (in km) by road, Google’s Distance Matrix API is a better solution.
This API can handle more than 1 original and more than 1 destination address in a single API request, so that’s what I need to have. I actually want to measure the “travel duration” in the current traffic (with delays) for or the following 3 trips:
Line 56: Convert the results from JSON to a php array
As shown in above screenshot that is added for line 42, three parts of results are visible. So for a results of 1 original and 1 destination address, the following information is available:
Distance
Duration
Duration in traffic
Line 61: To retrieve the “Distance” value from the array, add a variable with the following command: $distance = $result[‘rows’][0][‘elements’][0][‘distance’][‘value’];
Line 64: Save result in device value of virtual device in Homeseer.
Line 65: Save result in device string of virtual device in Homeseer.
Line 68: To retrieve the “Duration” value from the array, add a variable with the following command: $durationN = $result[‘rows’][0][‘elements’][0][‘duration’][‘value’];
Line 75: To retrieve the “Duration in traffic” value from the array, add a variable with the following command: $durationT = $result[‘rows’][0][‘elements’][0][‘duration_in_traffic’][‘value’];
Lines 88-141: Because my API url contains 3 routes, for each route, the 3 variables has to be declared.
Be aware of the different row results and elements. For the first route result it’s row 0 and element 0. For the second route result it’s row 1 and element 1, etc, etc.
When all variables results are done, the command for MySQL can be configured (sorry for the variable naming, but in first place I started with 1 original and 1 destination address):
Because I can’t run PHP scripts from Homeseer, I’ve a recurring event configured in the Task Scheduler in Windows, that start the php.exe program with the parameters of the script location:
Triggers: Will run every 5 minutes
Action: Start program
Program/script: C:\xampp\php\php.exe
Parameters: -f C:\xampp\htdocs\duration.php
Finally when the script will run succesfully, the MySQL table will be updated:
Show MySQL results in chart
Always nice to have is making the dat amore readable, so a nice Highcharts chart is created. On the right side of the chart a selection can be done to make results better readable:
In the download file, the query will retrieve the results for the last 3 days.
To-do improvements:
Setup fixed routes, which are not based on “best_guess” in the API