Currently, I am using the Google Maps distance matrix API and get the following result when I run the following code:
func configureRoute(origin:String,destination:String){
let jsonURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=place_id:\(origin)&destinations=place_id:\(destination)&key=MYAPIKEY"
guard let url = URL(string: jsonURL ) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
let dataAsString = String(data: data, encoding: .utf8)
print(dataAsString)
}.resume()
}
This is the result:
Optional("{\n \"destination_addresses\" : [ \"Pittsburgh, PA, USA\" ],\n \"origin_addresses\" : [ \"Philadelphia, PA, USA\" ],\n \"rows\" : [\n {\n \"elements\" : [\n {\n \"distance\" : {\n \"text\" : \"305 mi\",\n \"value\" : 490750\n },\n \"duration\" : {\n \"text\" : \"4 hours 48 mins\",\n \"value\" : 17257\n },\n \"status\" : \"OK\"\n }\n ]\n }\n ],\n \"status\" : \"OK\"\n}\n")
However from this result, I only want to get the duration of the distance which in this case is 4 hours and 48 mins. How would I only get the duration?
Upon trying a few suggestions, I placed my JSON url to get a formatted struct and got the following result:
struct Welcome: Codable {
let destinationAddresses, originAddresses: [String]
let rows: [Row]
let status: String
enum CodingKeys: String, CodingKey {
case destinationAddresses = "destination_addresses"
case originAddresses = "origin_addresses"
case rows, status
}
}
struct Row: Codable {
let elements: [Element]
}
struct Element: Codable {
let distance, duration: Distance
let status: String
}
struct Distance: Codable {
let text: String
let value: Int
}
Using this, I implemented the following code:
func configureRoute(origin:String,destination:String){
let jsonURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=place_id:\(origin)&destinations=place_id:\(destination)&key=MYAPIKEY"
guard let url = URL(string: jsonURL ) else {return}
print(jsonURL)
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
do{
let route = try JSONDecoder().decode(Element.self, from: data)
print (route.duration)
}
catch let jsonErr{
}
let dataAsString = String(data: data, encoding: .utf8)
// print(dataAsString)
}.resume()
}
But my result for route.duration is still nothing.