ios - 谷歌地图api在swift3中解析旅行持续时间数据

标签 ios json swift google-maps google-maps-api-3

我正在尝试使用 Google Directions API 解析估计的行程持续时间和两个航路点之间的距离,我希望将其显示在谷歌地图上。 这是API

   http://maps.googleapis.com/maps/api/directions/json?mode=walking&origin=13.0262523,77.5892838&destination=13.0282523,77.5892838&sensor=false

这是 json 结果

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJlaQiiroXrjsR4yct_s2meO0",
         "types" : [ "street_address" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "EmQxMTAtMTEyLCA3dGggQ3Jvc3MgUmQsIFYgLiBWIE5hZ2FyLCBLYXVzZXIgTmFnYXIsIERpbm51ciwgSGViYmFsLCBCZW5nYWx1cnUsIEthcm5hdGFrYSA1NjAwMzIsIEluZGlh",
         "types" : [ "street_address" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 13.0271681,
               "lng" : 77.5938656
            },
            "southwest" : {
               "lat" : 13.0246613,
               "lng" : 77.593385
            }
         },
         "copyrights" : "Map data ©2018 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "0.3 km",
                  "value" : 284
               },
               "duration" : {
                  "text" : "2 mins",
                  "value" : 101
               },
               "end_address" : "110-112, 7th Cross Rd, V . V Nagar, Kauser Nagar, Dinnur, Hebbal, Bengaluru, Karnataka 560032, India",
               "end_location" : {
                  "lat" : 13.0271681,
                  "lng" : 77.5938656
               },
               "start_address" : "75A, Dinnur Main Rd, P&T Colony, Ganga Nagar, Bengaluru, Karnataka 560032, India",
               "start_location" : {
                  "lat" : 13.0246613,
                  "lng" : 77.593385
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "26 m",
                        "value" : 26
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 8
                     },
                     "end_location" : {
                        "lat" : 13.0248884,
                        "lng" : 77.59343510000001
                     },
                     "html_instructions" : "Head \u003cb\u003enorth\u003c/b\u003e toward \u003cb\u003eDinnur Main Rd\u003c/b\u003e",
                     "polyline" : {
                        "points" : "c{nnAs}qxMm@K"
                     },
                     "start_location" : {
                        "lat" : 13.0246613,
                        "lng" : 77.593385
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.3 km",
                        "value" : 258
                     },
                     "duration" : {
                        "text" : "2 mins",
                        "value" : 93
                     },
                     "end_location" : {
                        "lat" : 13.0271681,
                        "lng" : 77.5938656
                     },
                     "html_instructions" : "At ArchFront Technologies, continue onto \u003cb\u003e7th Cross Rd\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003ePass by Anjali Mukerjee Health Total RT Nagar (on the left)\u003c/div\u003e\u003cdiv style=\"font-size:0.9em\"\u003eDestination will be on the right\u003c/div\u003e",
                     "polyline" : {
                        "points" : "q|nnA_~qxMG?qAM}@KSAgBUsDc@"
                     },
                     "start_location" : {
                        "lat" : 13.0248884,
                        "lng" : 77.59343510000001
                     },
                     "travel_mode" : "DRIVING"
                  }
               ],
               "traffic_speed_entry" : [],
               "via_waypoint" : []
            }
         ],
         "overview_polyline" : {
            "points" : "c{nnAs}qxMeEe@oH{@"
         },
         "summary" : "7th Cross Rd",
         "warnings" : [],
         "waypoint_order" : []
      }
   ],
   "status" : "OK"
}

这是代码

函数时间距离更新() {

 let request = URLRequest(url: URL(string: "http://maps.googleapis.com/maps/api/directions/json?&mode=driving&origin=\(currentlatlong)&destination=\(latlng)&sensor=false")!)

let session = URLSession.shared

let task = session.dataTask(with:request,completionHandler:{(d,response,error)in

    do{


        if let data = d{
            do{

                let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as! NSDictionary


                 if let studentsdata1 = jsonResult["routes"] as? NSArray {

                    if studentsdata1.count > 0 {

                     if let legs = studentsdata1[0]["legs"] as? NSArray

                     {

                        if legs.count > 0 {

                             if let duration = legs[0]["duration"] as? NSDictionary {

                            }

                        }
                        }
                    }

                }


            } catch
            {

            }

        }

    }
})
task.resume()
}

我搜索了很多方法,但没有找到任何东西,我想打印谷歌地图上标签中两个位置之间的持续时间和距离

最佳答案

这是解析距离和持续时间的代码

    var urlString  = String(format:"https://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternatives=%@&mode=%@&key=%@",soutLatitude,soutLongitude,destLatitude,destLongitude,"true","driving",google_directions_places_key)

    urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!


    let manager=AFHTTPRequestOperationManager()

    manager.responseSerializer = AFJSONResponseSerializer(readingOptions: JSONSerialization.ReadingOptions.allowFragments) as AFJSONResponseSerializer

    manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer

    manager.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/html", "text/plain", "text/json", "text/javascript", "audio/wav") as Set<NSObject>



    manager.post(urlString, parameters: nil, success: { (operation, response) in


        if(response != nil)
        {
            let parsedData = JSON(response!)

            print("parsedData12554 : \(parsedData)")

              print("parsed : \(parsedData["status"])")

            if(parsedData["status"] == "OK")
            {

                let routes = parsedData["routes"][0]

                print("Routesss260 \(routes)")

                let legs = routes["legs"][0]

                let distance = legs["distance"]

                let duration = legs["duration"]

                let disValue = distance["value"].double!

                let durValue = duration["value"].double! / 3600.0

                print("disValue250 \(disValue)")

                print("durValue250 \(durValue)")


                if(durValue != 0.0)
                {
                     self.speed = disValue / durValue
                }




            }


        }



    }) { (operation, error) in


          print("eeee2566\(error)")


    }

按照我正在使用的相同步骤

   pod 'SwiftyJSON' , '3.0.0'

   pod 'AFNetworking' , '2.5.4'

关于ios - 谷歌地图api在swift3中解析旅行持续时间数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083357/

相关文章:

objective-c - iOS UISearchBar 文本字段背景

ios - 使用数据、iOS、Swift 3 刷新表格的最有效内存方式是什么?

ios - 以编程方式获取设备的 iOS 版本

ios - Swift:无法将类型 '[Any]' 的值转换为指定类型 'NSString'

ios - iMessage 应用程序, "disallowed nested bundles"错误尝试使用二进制框架存档/上传

javascript - Json 循环不运行

Android,String无法转换为JSONObject

android - 用于任务管理的 android 和 web 应用程序(可能是 iOS)的裸 JSON、nosql db 或 sqlite

ios - 如何正确检查应用程序连接?

ios - 是否可以快速获取颜色名称