Swift 4.2: парсинг текста расстояния GoogleMaps Directions - PullRequest
0 голосов
/ 17 июня 2020

Добрый день,

Я пытался разобрать ветку Google Distance по URL-адресу, я новичок в сетевых и HTTP-запросах, но я понял идею кода для рисования ломаной линии и хотели бы реализовать анализ расстояния и продолжительности поездки в одном файле. Ниже мой код, который позволяет анализировать маршруты и расстояние.

//Gets path using the directions api
    func getDirectionsPathData(mapView: GMSMapView, from: CLLocationCoordinate2D, to: CLLocationCoordinate2D, onSuccess: @escaping (Any?) -> ()) {

        let fromStr = "\(from.latitude),\( from.longitude)"
        let toStr = "\(to.latitude),\( to.longitude)"

        //Makes final URL
        let url = URL(string : "https://maps.googleapis.com/maps/api/directions/json?origin=" + fromStr + "&destination=" + toStr + "&key=" + DIRECTION_API_KEY)


        guard let DirectionsURL = url else { return }

        //Makes Data task
        URLSession.shared.dataTask(with: DirectionsURL) {
            (data, response, error) in

            guard let data = data else { return }

            do {

                if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {


                    //Parse JSON to get directions
                   // let routes = json["routes"] as! NSArray
                    guard let routes = json["routes"] as? NSArray else {
                        print("error cannot unwrap")
                        return
                    }

                    let distance = json["routes"][0]["legs"][0]["distance"]["text"].string



                    //If there exists at least 1 route, return the value
                    if routes.count != 0 {


                        //Gets "overview_polyline" from the json
                        guard let routeOverviewPolyline = (routes.firstObject as? NSDictionary)?.value(forKey: "overview_polyline") as? NSDictionary else { return }

                        //guard let legs = (routes.firstObject as? NSDictionary)?.value(forKey: "legs") as? NSDictionary else { return }

                      //let distance = (legs.object(forKey: "distance.text") as! Float)
                       // print(distance)

                        //gets points of the polyline
                        let points = routeOverviewPolyline.object(forKey: "points")

                        //sends the points back to the Path manager
                        onSuccess(points)
                    }
                }

            } catch {
                print(error.localizedDescription)
            }

            }.resume()

    }

код расстояния заставил меня чесать голову весь день. Также было бы очень полезно указать, что сохранить.

Спасибо!

...