ios - 谷歌地图 iOS myLocation

标签 ios swift google-maps gps

我在谷歌地图的 myLocation 属性上苦苦挣扎,我总是得到 nil,并且无法弄清楚为什么。在我的 ViewDidLoad 中,我设置了以下内容

map.myLocationEnabled = true

并且在当用户想要获取他/她的位置时被调用的函数中,我运行这个:

print(map.myLocation)

我第一次知道它可能没有定位,但过一会儿我不应该定位吗?

最佳答案

我也有同样的想法,但实际上你需要先通过 Apple 的 CLLocationManager api 获取用户的位置。 导入 CoreLocation 并使您的 VC 遵守 CLLocationManagerDelegate 并使用 didUpdateLocations 方法获取用户的当前位置,然后将其反射(reflect)到 GMaps。

import UIKit
import GoogleMaps
import CoreLocation

class MapVC: UIViewController
{
    @IBOutlet weak var googleMap: GMSMapView!

    var locationManager: CLLocationManager = CLLocationManager()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
}

extension MapVC: CLLocationManagerDelegate
{
    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
    {
        switch status
        {
        case .AuthorizedAlways:
            print("Location AuthorizedAlways")
            googleMap.myLocationEnabled = true
            locationManager.startUpdatingLocation()

        case .AuthorizedWhenInUse:
            print("Location AuthorizedWhenInUse")
            googleMap.myLocationEnabled = true
            locationManager.startUpdatingLocation()

        case .Denied:
            print("Location Denied")
            googleMap.myLocationEnabled = false
            locationManager.stopUpdatingLocation()

        case .NotDetermined:
            print("Location NotDetermined")
            googleMap.myLocationEnabled = false
            locationManager.stopUpdatingLocation()

        case .Restricted:
            print("Location Restricted")
            googleMap.myLocationEnabled = false
            locationManager.stopUpdatingLocation()
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        if locations.count > 0
        {
            googleMap.camera = GMSCameraPosition.cameraWithTarget((locations.last?.coordinate)!, zoom: 10.0)
            googleMap.settings.myLocationButton = true
        }
    }
}

关于ios - 谷歌地图 iOS myLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39430399/

相关文章:

ios - 为什么我不能在 Swift 中使用从一个 UIViewController 传递到另一个(在控制台工作中打印数据)的数据设置标签?

iphone - 在 UIWebView 中的 iPhone 应用程序中显示带有方向的谷歌地图是否合法?

javascript - Google maps V3 用鼠标右键拖动 map ?

ios - 在 OpenGL ES 2.0 for iOS 中写入单 channel 像素缓冲区

ios - 我在 View 类中编写了一个tableView,但它无法显示数据源

ios - React Native 显示黑屏

ios - UIWebView 仅在添加到 View 时才起作用

swift - 是否可以在字符串的插值中包含一个方法? ( swift )

ios - 在 swift 中加载关于方向变化的 xib View

google-maps - 谷歌地图带阴影的折线