Traffic with Google Maps in Domoticz

Moderator: leecollings

raymond
Posts: 71
Joined: Monday 12 October 2015 15:46
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10232
Contact:

Re: Traffic with Google Maps in Domoticz

Post by raymond »

I've put some time frequencies in my script(s) which is an easy way of suppressing the log entries a little, especially the end piece where it writes a 0 if no updates. I've put this on 15 min.

The other thing I did is put in a weekend value, and if true it goes to end of the script right away ( goto ::done::)

@sjefk: I've also included to virtual switches to check, which are tied to my iPhone and geofencing. This means that I won't get any messages for my Home Work travel in the morning if I'm not actually home, same goes for the return from Office to home again. I've decleared these 2 switches at the top of the script, which I've shared below:

Code: Select all

---------------------------------
--Script to calculate duration and distance between two points using Google Maps
--Author   : woody4165 based on Neutrino Traffic with Waze, updated by G3rard
--Date     : 9 April 2016
---------------------------------
RayHome = 'RayHome' -- Domoticz name of the iPhone/Mobile device or other presence switch or virtual switch 
RayWork = 'RayWork'

commandArray={}

time = os.date("*t")
day = tonumber(os.date("%w"))

--idx of devices for capturing the travel minutes in both direction
idxtraffic='yourIDXhere'
idxroute='yourIDXhere'
--usual traveltime (mins)
usualtimehomework = 40
usualtimeworkhome = 40
-- Coordinates starting point
fromx="xx.xxxxxx"
fromy="xx.xxxxxx"
-- Coordinates destination point
tox="xx.xxxxxx"
toy="xx.xxxxxx"
--Google Api Key
key='your key here'

--determine workday (Mo-Fri)
if (day > 0 and day < 6) then
    week=true; weekend=false
else
    week=false; weekend=true
end

--determine time (7:00-9:00, 16:00-19:00)
if ((time.hour > 6 and time.hour < 9) or (time.hour == 9 and time.min < 1)) then
    mattina=true; sera=false
elseif ((time.hour > 16 and time.hour < 19) or (time.hour == 19 and time.min < 1)) then
    mattina=false; sera=true
else
    mattina=false; sera=false
end

if weekend then goto done
end

--calculate traveltime
function traveltime(fromx,fromy,tox,toy)
    --import JSON.lua library
    json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")()

    -- get data from Google Maps and decode it in gmaps
    local jsondata    = assert(io.popen('curl "https://maps.googleapis.com/maps/api/directions/json?origin='..fromx..','..fromy..'&destination='..tox..','..toy..'&departure_time=now&key='..key..'"'))
    local jsondevices = jsondata:read('*all')
    jsondata:close()
    local gmaps = json:decode(jsondevices)

    -- Read from the data table, and extract duration and distance in value. Divide distance by 1000 and duration_in_traffic by 60
    distance = gmaps.routes[1].legs[1].distance.value/1000
    duration = gmaps.routes[1].legs[1].duration_in_traffic.value/60
    summary = gmaps.routes[1].summary
    -- mins round the duration
    mins=math.ceil(duration)
    return mins
end

--weekday (Mo-Fri) and time between 7:00-9:00
if (week and mattina) and otherdevices[RayHome] == "On" then
    --every 15 minutes
    if((time.min % 15)==0) then
        traffic=traveltime(fromx,fromy,tox,toy)
        message=tostring(traffic)..' min reistijd naar werk '..("%02d:%02d"):format(time.hour, time.min)..' route '..tostring(summary)
      print(message)
      --send message if traveltime is longer than usual
      if(traffic > usualtimehomework) then
      --os.execute('curl --data chat_id=xxxxxxxx --data-urlencode "text='..message..'"  "https://api.telegram.org/botxxxxxxxxxxxxx/sendMessage" ')
          commandArray['SendNotification']=message
      end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}
    end

--weekday (Mo-Thu) and time between 16:00-19:00
elseif (week and sera) and otherdevices[RayWork] == "On" then
    --every 15 minutes
    if((time.min % 15)==0) then
        traffic=traveltime(tox,toy,fromx,fromy)
        message=tostring(traffic)..' min reistijd naar huis '..("%02d:%02d"):format(time.hour, time.min)..' route '..tostring(summary)
      print(message)
      --send message if traveltime is longer than usual
      if(traffic > usualtimeworkhome) then
      --os.execute('curl --data chat_id=xxxxxx --data-urlencode "text='..message..'"  "https://api.telegram.org/botxxxxxxxxx/sendMessage" ')
          commandArray['SendNotification']=message
      end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}

end
    -- set device to 0 to prevent device get the last value after working hour
elseif((time.min % 15)==0) then
    zero=0
    commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(zero)}
    commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(zero)}
end
::done::
return commandArray
I hope this helps you guys out somehow, it works for me :)
Martijn85
Posts: 53
Joined: Wednesday 20 January 2016 20:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by Martijn85 »

Can someone tell me witch API i must use for this script?

I keep ketting this message:

Code: Select all

{
   "error_message" : "This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/directions_backend?project=_",
   "routes" : [],
   "status" : "REQUEST_DENIED"
}
I already tried: Google Maps Embed API, Google Maps JavaScript API and Google Places API Web Service.

PS: API is already activated.

Edit: I checked the old posts: It's "The Google Maps Directions API"
Martijn85
Posts: 53
Joined: Wednesday 20 January 2016 20:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by Martijn85 »

Strange, with the API working now the time on the switches (text and custom) keeps only 1 Min every update?
febalci
Posts: 331
Joined: Monday 03 July 2017 19:58
Target OS: NAS (Synology & others)
Domoticz version:
Contact:

Re: Traffic with Google Maps in Domoticz

Post by febalci »

Had to work on the curl line in my case to make it work. Using Domoticz as a Synology package. There's no problem when using curl in the command line, however in LUA event script it always gives me the error:

Code: Select all

curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.haxx.se/docs/sslcerts.html
So, i had to use -k switch in curl line to make a non-trustable connection to make it work...
MAidEN
Posts: 17
Joined: Sunday 07 December 2014 15:14
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Traffic with Google Maps in Domoticz

Post by MAidEN »

Hi,

I try to use this script but my sensors update each minute only with 0 value all the time (is the same on week / weekend / morning or afternoon.

I have one sensor on text and one custom sensor but the script go directly at the end of script and set 0 like is always after working hour.

When I try the URL with my x and y I have a good result like this :

Code: Select all

      "distance" : {
                  "text" : "40,1 km",
                  "value" : 40127
               },
               "duration" : {
                  "text" : "35 minutes",
                  "value" : 2093
My script if we can help me :

Code: Select all

---------------------------------
--Script to calculate duration and distance between two points using Google Maps
--Author   : woody4165 based on Neutrino Traffic with Waze, updated by G3rard
--Date     : 9 April 2016 
---------------------------------
commandArray={}

time = os.date("*t")
day = tonumber(os.date("%w"))

--idx of devices for capturing the travel minutes in both direction
idxtraffic='272'
idxroute='271'
--usual traveltime (mins)
usualtimehomework = 40
usualtimeworkhome = 40
-- Coordinates starting point
fromx="my from x"
fromy="my from y"
-- Coordinates destination point
tox="my to x"
toy="my to y"
--Google Api Key
key='my key'

--determine workday (Mo-Fri)
if (day > 0 and day < 6) then
week=true; weekend=false
else
week=false; weekend=true
end

--determine time (7:00-9:00, 17:00-19:00)
if ((time.hour > 7 and time.hour < 9) or (time.hour == 9 and time.min < 1)) then
 matin=true; soir=false
elseif ((time.hour > 17 and time.hour < 19) or (time.hour == 19 and time.min < 1)) then
  matin=false; soir=true
else
  matin=false; soir=false
end


--calculate traveltime
function traveltime(fromx,fromy,tox,toy)
    --import JSON.lua library
    json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")()

    -- get data from Google Maps and decode it in gmaps
    local jsondata    = assert(io.popen('curl "https://maps.googleapis.com/maps/api/directions/json?origin='..fromx..','..fromy..'&destination='..tox..','..toy..'&departure_time=now&key='..key..'"'))
    local jsondevices = jsondata:read('*all')
    jsondata:close()
    local gmaps = json:decode(jsondevices)

    -- Read from the data table, and extract duration and distance in value. Divide distance by 1000 and duration_in_traffic by 60
    distance=gmaps.routes[1].legs[1].distance.value/1000
    duration=gmaps.routes[1].legs[1].duration_in_traffic.value/60
    summary=gmaps.routes[1].summary
    -- mins round the duration
    mins=math.ceil(duration)
    return mins
end

--weekday (Mo-Fri) and time between 7:00-9:00
if (week and matin) then
    --every 15 minutes
    if((time.min % 15)==0) then
	    traffic_Home2Work=traveltime(fromx,fromy,tox,toy)
		message=tostring(traffic_Home2Work)..'min pour aller au bureau '..("%02d:%02d"):format(time.hour, time.min)..' route'..tostring(summary)
     print(message)
      --send message if traveltime is longer than usual
     --if(traffic_Home2Work > usualtimehomework) then
       --os.execute('curl --data chat_id=xxxxxxxx --data-urlencode "text='..message..'"  "https://api.telegram.org/botxxxxxxxxxxxxx/sendMessage" ')
      --commandArray['SendNotification']=message
     --end
     --return a text to the device (eg. 12 mins)
      commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic_Home2Work)}
      commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}
	end

--weekday (Mo-Thu) and time between 16:00-19:00
elseif (week and soir) then
    --every 15 minutes
    if((time.min % 15)==0) then
        traffic_Work2Home=traveltime(tox,toy,fromx,fromy)
        message=tostring(traffic_Work2Home)..'min pour aller a la maison '..("%02d:%02d"):format(time.hour, time.min)..' route '..tostring(summary)
      print(message)
     -- send message if traveltime is longer than usual
		--if(traffic_Work2Home > usualtimeworkhome) then
		--os.execute('curl --data chat_id=xxxxxx --data-urlencode "text='..message..'"  "https://api.telegram.org/botxxxxxxxxx/sendMessage" ')
		--commandArray['SendNotification']=message
		--end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic_Work2Home)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}

    end
else
    -- set device to 0 to prevent device get the last value after working hour
			zero=0
			commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(zero)}
			commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(zero)}
end

return commandArray
Thanks a lot !
User avatar
krazny
Posts: 27
Joined: Saturday 01 November 2014 23:31
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by krazny »

Is this still applicable?

Had to do a reinstall of Domoticz recently and wanted to implement this again.

Unfortunately I didn't save my script (with Google API key) and must start from scratch.
I am unable to create a (new) API key. Isn't it free anymore? :?:
Raspberry Pi, Aeon Z-Stick, Fibaro Motion Sensor, 4x Fibaro Wall Plug, 2x Fibaro Dimmer, Netatmo Weatherstation
User avatar
EdwinK
Posts: 1820
Joined: Sunday 22 January 2017 21:46
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Rhoon
Contact:

Re: Traffic with Google Maps in Domoticz

Post by EdwinK »

I don't believe the API's are free anymore. or at least very complicated. You will get a $200 credit each month, and they will first use this before you getting billed. Can't check it, as i can't login anymore
Last edited by EdwinK on Thursday 06 September 2018 20:55, edited 1 time in total.
Running latest BETA on a Pi-3 | Toon® Thermostat (rooted) | Hue | Tuya | IKEA tradfri | Dashticz V3 on Lenovo Huawei Tablet | Conbee
User avatar
krazny
Posts: 27
Joined: Saturday 01 November 2014 23:31
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by krazny »

EdwinK wrote: Thursday 06 September 2018 20:32 I don't believe the API's are free anymore. or at least very complicated.
So that means this isn't applicable anymore...
Such a shame. Since it was a really nice feature!
Raspberry Pi, Aeon Z-Stick, Fibaro Motion Sensor, 4x Fibaro Wall Plug, 2x Fibaro Dimmer, Netatmo Weatherstation
maryannlee9
Posts: 2
Joined: Monday 08 April 2019 11:04
Target OS: Windows
Domoticz version:

Re: Traffic with Google Maps in Domoticz

Post by maryannlee9 »

Joining previous commenters, is this still actual? I've got a project related to some travel maps , but I feel like there are many issues yet I can't cope with yet.
Joep123
Posts: 56
Joined: Monday 26 March 2018 18:44
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Contact:

Re: Traffic with Google Maps in Domoticz

Post by Joep123 »

EdwinK wrote: Thursday 06 September 2018 20:32 I don't believe the API's are free anymore. or at least very complicated. You will get a $200 credit each month, and they will first use this before you getting billed. Can't check it, as i can't login anymore
It's still usable.... 1,000 requests costs $5 and you will get $200 for free each month.
((200/5)*1000)/30 = 1,333 free requested each day!
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest