我在谷歌地图的 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/