如何使用Google Maps iOS SDK在地图上显示用户的位置?
我尝试在self.myMapView(MKMapView)中查找.myLocation属性,但找不到。
有人能一步一步地告诉我如何在地图上显示我的用户的位置吗?
发布于 2015-11-26 20:00:28
创建GMSMapView和CLLocationManager的属性,如
@IBOutlet弱var mapView: GMSMapView!
CLLocationManager locationManager = var ()
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
}
}//标记:- 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是布尔属性,也不要忘记将'NSLocationWhenInUseUsageDescription‘键添加到Info.plist文件中

发布于 2015-11-26 18:57:13
此代码将标记设置为所需的coordinated。您可以通过CoreLocation框架(CLLocationManagerDelegate)获取当前位置坐标
self.mapView.camera = GMSCameraPosition.cameraWithLatitude(latitude, longitude: longitude, zoom: 6)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.title = "Marker title"
marker.map = self.mapViewhttps://stackoverflow.com/questions/33936598
复制相似问题