Направление Google Map для iOS swift - PullRequest
0 голосов
/ 27 мая 2020

Я пытаюсь указать направление на карте Google для своего проекта, но получаю ошибку значения маршрута -> (индекс вне диапазона) вот часть моего кода, который я сделал в Xcode Swift

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

import UIKit
import GoogleMaps
import GooglePlaces

class DirectionMapViewController: UIViewController,GMSMapViewDelegate,CLLocationManagerDelegate {


    let locationManager = CLLocationManager()
    var currentLocation: CLLocation!

    @IBOutlet weak var MyMapView: GMSMapView!
    @IBOutlet weak var mybutton: UIButton!
      override func viewDidLoad() {


        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges()
        locationManager.requestLocation()
        MyMapView.isMyLocationEnabled = true
        MyMapView.settings.myLocationButton = true
        MyMapView.settings.compassButton = true
        MyMapView.settings.zoomGestures = true
        MyMapView.delegate = self
       // MyMapView.camera = camera

        currentLocation = locationManager.location
        print(currentLocation.coordinate.latitude)
        print(currentLocation.coordinate.longitude)

        super.viewDidLoad()

        let marker1 = GMSMarker()
        marker1.position = CLLocationCoordinate2D(latitude: 35.1623, longitude: 33.3178)
        marker1.title = "P1"
        marker1.snippet = "28 Oct Street"
        marker1.map = MyMapView

        let marker2 = GMSMarker()
        marker2.position = CLLocationCoordinate2D(latitude: 35.1658, longitude: 33.3147)
        marker2.title = "P2"
        marker2.snippet = "Makedonitissis 46, Nicosia 2417"
        marker2.map = MyMapView

        let marker3 = GMSMarker()
        marker3.position = CLLocationCoordinate2D(latitude: 35.1600, longitude: 33.3770)
        marker3.title = "P3"
        marker3.snippet = "Kallipoleos 75, Nicosia 1678"
        marker3.map = MyMapView

        let marker4 = GMSMarker()
        marker4.position = CLLocationCoordinate2D(latitude: 35.1602,  longitude: 33.3390)
        marker4.title = "P4"
        marker4.snippet = "Diogenis Str 6 Nicosia CY  2404"
        marker4.map = MyMapView

        let marker5 = GMSMarker()
        marker5.position = CLLocationCoordinate2D(latitude: 35.1673,  longitude: 33.3277)
        marker5.title = "P5"
        marker5.snippet = "Neas Egkomis 4  Egkomi"
        marker5.map = MyMapView

        let marker6 = GMSMarker()
        marker6.position = CLLocationCoordinate2D(latitude: 35.1680,  longitude: 33.3375)
        marker6.title = "P6"
        marker6.snippet = "Neas Egkomis 4  Egkomi"
        marker6.map = MyMapView


        let marker7 = GMSMarker()
        marker7.position = CLLocationCoordinate2D(latitude: 35.1460,  longitude: 33.3357)
        marker7.title = "P7"
        marker7.snippet = "Neas Egkomis 4  Egkomi"
        marker7.map = MyMapView

        let marker8 = GMSMarker()
        marker8.position = CLLocationCoordinate2D(latitude: 35.1580,  longitude: 33.3275)
        marker8.title = "P8"
        marker8.snippet = "Neas Egkomis 4  Egkomi"
        marker8.map = MyMapView
}
func locationManager(_ manager: CLLocationManager,didFailWithError error: Error) {
      print(error)
    }
    func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {

        let location = locations.last
        MyMapView.camera = GMSCameraPosition(target: location!.coordinate,zoom: 15)
        self.locationManager.stopUpdatingLocation()


      }

 func getRouteSteps(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {

        let session = URLSession.shared

        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving&key=\("My_API_Key")")!

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

            guard error == nil else {
                print("Here Here")
                print(error!.localizedDescription)
                return
            }

            guard let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else {

                print("error in JSONSerialization")
                print(error)
                return

            }



            guard let routes = jsonResult["routes"] as? [Any] else {
                return
            }

            guard let route = routes[0] as? [String: Any] else {
                return
            }

            guard let legs = route["legs"] as? [Any] else {
                return
            }

            guard let leg = legs[0] as? [String: Any] else {
                return
            }

            guard let steps = leg["steps"] as? [Any] else {
                return
            }
              for item in steps {

                guard let step = item as? [String: Any] else {
                    return
                }

                guard let polyline = step["polyline"] as? [String: Any] else {
                    return
                }

                guard let polyLineString = polyline["points"] as? String else {
                    return
                }

                //Call this method to draw path on map
                DispatchQueue.main.async {
                    self.drawPath(from: polyLineString)
                }

            }
        })
        task.resume()
    }
    func drawPath(from polyStr: String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.map = MyMapView // Google MapView


        let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: currentLocation.coordinate, coordinate: marker1.position ))
        MyMapView.moveCamera(cameraUpdate)
        let currentZoom = MyMapView.camera.zoom
        MyMapView.animate(toZoom: currentZoom - 1.4)
    }
 @IBAction func mybutton(_ sender: Any) {
        getRouteSteps(from: currentLocation.coordinate, to: marker1.position)

    }
   }

, пока я нажимаю на кнопку, отображается эта ошибка, показанная на изображении -> enter image description here

примечание: я добавляю файл модуля, получаю свой ключ API и помещаю его в URL-адрес выше и в appDelegate

Есть идеи? что не так? где моя ошибка? !!

заранее спасибо

...