在地图上添加用户当前位置的摄像头

时间:2018-01-17 09:44:10

标签: ios swift google-maps swift4

我在viewController中添加了这段代码

import UIKit
import CoreLocation
import GoogleMaps

class CourseClass2: UIViewController, UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate {


@IBOutlet weak var mapView: GMSMapView!

}

和此扩展程序

extension CourseClass2:  CLLocationManagerDelegate {

    func determineMyCurrentLocation() {

        guard currentLocation == nil else {
            return
        }

        locationManager = CLLocationManager()
        locationManager?.delegate = self 
        locationManager?.desiredAccuracy = kCLLocationAccuracyBest
        locationManager?.requestWhenInUseAuthorization()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation

        manager.stopUpdatingLocation()

        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")

        didReceiveUserLocation(userLocation)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error \(error)")
        errorGettingCurrentLocation(error.localizedDescription)
    }

    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            locationManager?.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        } else if status == .denied || status == .restricted {
            errorGettingCurrentLocation("Location access denied")
        }
    }

    func errorGettingCurrentLocation(_ errorMessage:String) {
        let alert = UIAlertController.init(title: "Error", message: errorMessage, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
}
}

获取用户位置。现在我想在我的控制器的viewDidLoad中添加一个像let camera = GMSCameraPosition.camera(withLatitude: , longitude: , zoom: 14)这样的相机用户位置,但是如何在这一行中使用我在扩展中找到的用户当前位置的纬度和经度?

1 个答案:

答案 0 :(得分:1)

您需要在locationManager.startUpdatingLocation()中调用viewDidLoad(),其中locationManager是CLLocationManager对象。检索到当前位置后,将调用didUpdateLocations委托方法,您可以按如下方式设置摄像机位置:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation = locations.last

    let location = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude, zoom: 16.0)

    mapView.animate(to: location)

}