【发布时间】:2018-01-17 09:44:09
【问题描述】:
我在 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) 这样的摄像头在用户位置上,但是我怎样才能在这条线上使用我在扩展中找到的用户当前位置的纬度和经度?
【问题讨论】:
-
明显使用变量。
-
你能给我一个例子吗?我有点困惑
-
将收到的用户位置存储在变量中。声明一个变量 var userLocation:CLLocation ,当你在扩展中收到它时,然后分配它。然后像这样使用它: let camera = GMSCameraPosition.camera(withLatitude:userLocation.coordinate.latitude , longitude:userLocation.coordinate.longitude , zoom: 14)
-
好的,但这是我的问题,userLocation 在我的扩展程序中是一个常量,所以如果我在控制器的 viewDidLoad 中写入 userLocation.coordinate 它不会读取它
-
我的意思是在你的类 CourseClass2 中添加一个变量(即类级别变量)它将适用于类和扩展。您还想在视图中编写相机方法确实加载但位置委托需要一些时间才能返回当前位置。所以只需为相机创建一个方法并从委托方法中调用它。或者您可以使用 not nill check view did load ,但它永远不会被按时调用。
标签: ios swift google-maps swift4