Google map api在swift3中解析旅行持续时间数据

时间:2018-01-03 18:44:58

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

我尝试使用Google Directions API解析估计的行程持续时间和两个航路点之间的距离,我想在Google地图上进行此操作。 这是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"
}

这是代码

func timedistanceupdate()    {

 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()
}

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

1 个答案:

答案 0 :(得分:0)

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

    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'