/
GoogleAPI.hs
56 lines (45 loc) · 1.83 KB
/
GoogleAPI.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{-# LANGUAGE OverloadedStrings #-}
module GoogleAPI where
import Network.Stream
import Network.URI
import Network.HTTP.Conduit
import Network.HTTP.Base
import Network.HTTP.Headers
import Data.Maybe
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as BS
import qualified JsonParser as JP
import JsonParser
directionsUrl = "https://maps.googleapis.com/maps/api/directions/json?"
{- DO NOT PUSH API KEY -}
apiKey = ""
{- Function to do make HTTPS GET request to Google's Direction API -}
getDirectionFromApi :: String -> String -> IO(LBS.ByteString)
getDirectionFromApi origin destination = do
initReq <- parseUrlThrow (directionsUrl)
let r = initReq {method = "GET"}
let request = setQueryString [("origin", Just (BS.pack origin))
,("destination", Just (BS.pack destination))
,("mode", Just "transit")
,("key", Just apiKey)] r
manager <- newManager tlsManagerSettings
res <- httpLbs request manager
return . responseBody $ res
{- Function to store JSON file externally -}
storeDirectionInExternalJson :: String -> String -> IO()
storeDirectionInExternalJson origin destination = do
routeInJson <- getDirectionFromApi origin destination
LBS.writeFile "route.json" routeInJson
{- Function to quickly grab list of Route from JSON -}
routes :: Value -> Parser [JP.Route]
routes = withObject "Routes" $ \o -> o .: "routes"
{- Function to get list of Route from loaded JSON -}
getDirectionFromFile :: String -> String -> IO ([JP.Route])
getDirectionFromFile origin destination = do
storeDirectionInExternalJson origin destination
bs <- LBS.readFile "route.json"
let maybeRoutes = parseMaybe routes =<< decode bs
let routeList = JP.checkRoutes maybeRoutes
return routeList