我有以下代码,它应该基本上检测位置(如果位置服务打开),然后返回上一页并显示坐标(单击按钮时) .
@IBOutlet var mapView:GMSMapView!//在Storyboard上添加Google Map检查var locationManager:CLLocationManager! var viewController:ViewController! //保存前一个控制器的对象以返回该位置
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager = CLLocationManager() // Intialize the location manager
locationManager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Methos to change the MApType
@IBAction func changeMaptoEarthView()
{
self.mapView.mapType = kGMSTypeSatellite
}
@IBAction func changeMaptoMapView()
{
self.mapView.mapType = kGMSTypeNormal
}
//Method to get UserLocation
@IBAction func sendLocationtoPreviousView()
{
viewController.locationRecieved(locationManager.location)
self.performSegueWithIdentifier("backSegue", sender: nil)
}
@IBAction func addUserLocation() //Detect location click event
{
if(CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse) // If already have location access
{
locationManager.startUpdatingLocation()
}
else if (CLLocationManager.authorizationStatus() == .Denied)// If location access is denied in setting
{
UIAlertView(title: "Permission", message: "Please allow location services in setting", delegate: nil, cancelButtonTitle: "ok").show()
}
else
{
locationManager.requestWhenInUseAuthorization() // Ask user permission if permission not given
}
}
//CLLocation Manager Delegate methoda
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
self.mapView.clear() // clear all overlay on Map
self.mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
// Adding pin on Current location
var marker = GMSMarker()
marker.position = location.coordinate
marker.snippet = "My Location"
marker.appearAnimation = kGMSMarkerAnimationPop
marker.map = mapView
locationManager.stopUpdatingLocation()
}
}
该应用程序在模拟器中工作,直到我说回去,然后它在此行抛出零错误消息:
viewController.locationRecieved(locationManager.location)
可能是什么原因?我可以看到 Map 上的图钉虽然 Map 没有显示任何图形,除了下面的谷歌徽标
2 回答
CLLocationManager
上的location
属性是可选的 - 意味着它可以是nil . 根据文档,如果没有检索到位置数据,那将是零 .您没有显示如何定义
viewController.locationRecieved
,但我的猜测是您已将CLLocation
参数配置为隐式展开的可选项(即,使用"!") . 将nil传递给这样的参数会导致崩溃 .如果您在视图(GMSMapView的子类)中没有看到 Map 图形,这是因为Google Map API密钥,可能您尚未在应用委托中设置它或未正确设置!
确保您已使用Google应用套件ID和您的帐户设置了正确的Google API密钥 . 你必须在app app中设置下面的代码,做didFinishLaunchingWithOptions函数: