在Swift上当前位置和用户所选位置之间绘制路线

问题描述

我正在尝试通过iOS使用Google Map SDK创建一个可绘制用户当前位置和所选位置之间路线的应用程序。 但是,似乎当我尝试获取所选位置的CLLocationCoordinate2D时,得到的坐标为(-180,-180),因此无法绘制路线。 我不太确定如何获取所选目的地的坐标,因为我刚开始使用Swift。

我在ViewController中的以下代码如下:

import UIKit
import GoogleMaps
import GooglePlaces
import MapKit

class MapViewController: UIViewController {

  // [START maps_ios_current_place_declare_params]
  var locationManager: CLLocationManager!
  var currentLocation: CLLocation?
  var mapView: GMSMapView!
  var placesClient: GMSPlacesClient!
  var zoomLevel: Float = 15.0
    var originalLoc: CLLocationCoordinate2D?
    var destinationLoc : CLLocationCoordinate2D?
    
  // [END maps_ios_current_place_declare_params]
    
  // [START maps_ios_current_place_places_params]
  // An array to hold the list of likely places.
  var likelyPlaces: [GMSPlace] = []

  // The currently selected place.
  var selectedplace: GMSPlace?
  // [END maps_ios_current_place_places_params]

  // A default location to use when location permission is not granted.
  let defaultLocation = CLLocation(latitude: -33.869405,longitude: 151.199)
    

  // [START maps_ios_current_place_unwindtomain]
  // Update the map once the user has made their selection.
  @IBAction func unwindToMain(segue: UIStoryboardSegue) {
    // Clear the map.
    mapView.clear()

    // Add a marker to the map.
    if selectedplace != nil {
      let marker = GMSMarker(position: (self.selectedplace?.coordinate)!)
      marker.title = selectedplace?.name
      marker.snippet = selectedplace?.formattedAddress
      marker.map = mapView
      let destinationLoc = selectedplace!.coordinate
      let originalLoc: CLLocationCoordinate2D = locationManager.location!.coordinate
      drawRoute(from: originalLoc,to: destinationLoc)
    }

    listLikelyPlaces()
    
  }
  // [END maps_ios_current_place_unwindtomain]

  override func viewDidLoad() {
    super.viewDidLoad()
    
    
    // [START maps_ios_current_place_init_params]
    // Initialize the location manager.
    locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.distanceFilter = 50
    locationManager.startUpdatingLocation()
    locationManager.delegate = self

    placesClient = GMSPlacesClient.shared()
    // [END maps_ios_current_place_init_params]

    // [START maps_ios_current_place_create_a_map]
    // Create a map.
    let camera = GMSCameraPosition.camera(withLatitude: defaultLocation.coordinate.latitude,longitude: defaultLocation.coordinate.longitude,zoom: zoomLevel)
    mapView = GMSMapView.map(withFrame: view.bounds,camera: camera)
    mapView.settings.myLocationButton = true
    mapView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
    mapView.isMyLocationEnabled = true

    // Add the map to the view,hide it until we've got a location update.
    view.addSubview(mapView)
    mapView.isHidden = true
    // [END maps_ios_current_place_create_a_map]

    listLikelyPlaces()

  }

  // [START maps_ios_current_place_list_likely_places]
  // Populate the array with the list of likely places.
  func listLikelyPlaces() {
    // Clean up from prevIoUs sessions.
    likelyPlaces.removeAll()

    placesClient.findplaceLikelihoodsFromCurrentLocation(withPlaceFields: .name) { (placeLikelihoods,error) in
      guard error == nil else {
        // Todo: Handle the error.
        print("Current Place error: \(error!.localizedDescription)")
        return
      }

      guard let placeLikelihoods = placeLikelihoods else {
        print("No places found.")
        return
      }
      
      // Get likely places and add to the list.
      for likelihood in placeLikelihoods {
        let place = likelihood.place
        self.likelyPlaces.append(place)
      }
    }
  }
  // [END maps_ios_current_place_list_likely_places]
    func drawRoute(from originPosition: CLLocationCoordinate2D,to destinationPosition: CLLocationCoordinate2D) {
         let request = MKDirections.Request()
         request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destinationPosition))
         request.source = MKMapItem(placemark: MKPlacemark(coordinate: originPosition))
         request.requestsAlternateRoutes = false

         let direction = MKDirections(request: request)
         direction.calculate() {
             (response,error) in
             if let r = response,r.routes.count > 0 {
                 for route in r.routes {
                     let n = route.polyline.pointCount
                     let coordinates = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: n)
                     route.polyline.getCoordinates(coordinates,range: NSMakeRange(0,n))
                     let path = GMSMutablePath()
                     for index in 0..<n {
                         path.add(coordinates[index])
                     }
                     let polyline = GMSpolyline.init(path: path)
                     polyline.strokeWidth = 3
                     let bounds = GMSCoordinateBounds(path: path)
                     self.mapView!.animate(with: GMSCameraUpdate.fit(bounds,withPadding: 30.0))
                     polyline.map = self.mapView
                 }
             }
         }
     }

  // [START maps_ios_current_place_segue]
  // Prepare the segue.
  override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    if segue.identifier == "seguetoSelect" {
      if let nextViewController = segue.destination as? PlacesViewController {
        nextViewController.likelyPlaces = likelyPlaces
      }
    }
  }
  // [END maps_ios_current_place_segue]
}

// [START maps_ios_current_place_location_manager_delegate]
// Delegates to handle events for the location manager.
extension MapViewController: CLLocationManagerDelegate {

  // Handle incoming location events.
    func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
        let location: CLLocation = locations.last!
        print("Location: \(location)")
        let camera = GMSCameraPosition.camera(withLatitude:location.coordinate.latitude,longitude: location.coordinate.longitude,zoom: zoomLevel)
        if mapView.isHidden {
            mapView.isHidden = false
            mapView.camera = camera
            
        } else {
            mapView.animate(to: camera)
            
        }
        listLikelyPlaces()
    }

  // Handle authorization for the location manager.
  func locationManager(_ manager: CLLocationManager,didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .restricted:
      print("Location access was restricted.")
    case .denied:
      print("User denied access to location.")
      // display the map using the default location.
      mapView.isHidden = false
    case .notDetermined:
      print("Location status not determined.")
    case .authorizedAlways: fallthrough
    case .authorizedWhenInUse:
      print("Location status is OK.")
    @unkNown default:
      fatalError()
    }
  }

  // Handle location manager errors.
  func locationManager(_ manager: CLLocationManager,didFailWithError error: Error) {
    locationManager.stopUpdatingLocation()
    print("Error: \(error)")
  }
}
// [END maps_ios_current_place_location_manager_delegate]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...