谷歌地图SDK,iOS,无法获取myLocation

时间:2014-12-20 09:13:07

标签: ios swift google-maps-sdk-ios

我想使用Google Maps SDK在iOS应用上显示我的位置。但是,它无法获取我的位置。我提到了以下文件document1document2

这是我的代码。它只显示英国的地图。

请帮我解决问题。

import UIKit

class SearchVC: UIViewController,CLLocationManagerDelegate{

///Google Map
@IBOutlet weak var mapView:GMSMapView!
let locationManager =  CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func locationManager(manager:CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus){
    if status == .AuthorizedWhenInUse{

        locationManager.startUpdatingLocation()

        mapView.myLocationEnabled = true
        mapView.settings.myLocationButton = true
    }
}
func locationManager(manager:CLLocationManager!, didUpdateLocations locations:[AnyObject]!){
    if let location = locations.first as? CLLocation{

        mapView.camera = GMSCameraPosition(target:location.coordinate, zoom:15,bearing:0, viewingAngle:0)
        locationManager.stopUpdatingLocation()
    }
}
}

2 个答案:

答案 0 :(得分:0)

下载一些代码来解析您的位置...我认为您只是在解决要加载的地图视图的位置信息时遇到问题

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
    if (error != nil) {
        println("Error:" + error.localizedDescription)
        return
    }

    if placemarks.count > 0 {
        let pm = placemarks[0] as CLPlacemark
        pm.location.coordinate;
        mapView.camera = GMSCameraPosition(target:pm.location.coordinate, zoom:15,bearing:0, viewingAngle:0)
        locationManager.stopUpdatingLocation()

    }else {
        println("Error with data")
    }
}

我还没有编译这段代码而且我不是很精明,但希望这有助于

要更改您的位置,请转到Edit Scheme... enter image description here

然后选择您要模拟的任何位置 enter image description here

答案 1 :(得分:0)

问题:

func locationManager(manager:CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus)

只有在授权状态发生变化时才会真正调用此函数。例如,当您第一次运行应用程序时,它会要求启用位置服务。一旦你点击是,这个功能就会运行。下次运行应用程序时,授权状态不会更改,因为之前已启用。

修复:

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.startUpdatingLocation()

        mapView.myLocationEnabled = true
        mapView.settings.myLocationButton = true
    }
}

现在每次加载视图时,它都会开始更新位置,而不是授权状态更改时。确保还将key:value对添加到info.plist(NSLocationWhenInUseUsageDescription:{authorizatinon message string})。