如何使用Google Maps iOS SDK在地图上显示用户的位置?
我尝试在.myLocation
中找到self.myMapView(MKMapView)
属性,但我找不到它。
有人可以一步一步地向我解释如何在地图上显示我的用户位置吗?
答案 0 :(得分:2)
为GMSMapView和CLLocationManager创建属性,如
@IBOutlet weak var mapView:GMSMapView!
var locationManager = CLLocationManager()
var didFindMyLocation = false
并在viewdidload方法中为地图视图添加观察者,以便进行位置更新,如下所示
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(48.857165, longitude: 2.354613, zoom: 2.0)
mapView.camera = camera
mapView.delegate = self
mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if !didFindMyLocation {
let myLocation: CLLocation = change![NSKeyValueChangeNewKey] as! CLLocation
mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom: 10.0)
mapView.settings.myLocationButton = true
didFindMyLocation = true
}
}
// MARK: - CLLocationManagerDelegate
extension MapViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
mapView.myLocationEnabled = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
}
didFindMyLocation是bool属性,也不要忘记添加&#39; NSLocationWhenInUseUsageDescription&#39; Info.plist文件的关键
答案 1 :(得分:0)
此代码将标记设置为所需的协调。 您可以通过CoreLocation框架(CLLocationManagerDelegate)获取的当前位置坐标
self