【问题标题】:Issues getting user location from CLLocationManager (Google Maps API)从 CLLocationManager (Google Maps API) 获取用户位置的问题
【发布时间】:2017-02-15 23:16:53
【问题描述】:

我正在开发一个使用 Google Maps API 的 iPhone 应用程序,但在获取用户的当前位置时遇到问题,以便地图在他们的位置上打开。

我现在已经花了几天的时间来解决编译器错误,但它仍然不能正常工作。地图显示了,但仅在我为 long 和 lat 变量提供的初始坐标处。我认为这与CLLoationManager() 有关。

在模拟器上更新位置没有任何结果,我觉得我犯了一个菜鸟错误,我只是不知道是什么。和建议?

    import UIKit
    import CoreLocation
    import GoogleMaps


class ViewController: UIViewController, CLLocationManagerDelegate {

var long:Double = -0.13
var lat:Double = 51.0

let locationManager = CLLocationManager()

override func loadView() {
    // Create a GMSCameraPosition that tells the map to display the

    //user location stuff
    self.locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()


    let camera = GMSCameraPosition.camera(withLatitude: CLLocationDegrees(lat), longitude: CLLocationDegrees(long), zoom: 5.0)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

    view = mapView
    mapView.showUserLocation = true
    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 51.51 , longitude: -0.13)
    marker.title = "Test"
    marker.snippet = "This is a test"
    marker.map = mapView
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //i think this is the problem area
    let userLocation = locations.last!
    long = userLocation.coordinate.longitude
    lat = userLocation.coordinate.latitude

    self.locationManager.stopUpdatingLocation()

}
}

【问题讨论】:

    标签: swift google-maps-api-3 core-location cllocationmanager user-location


    【解决方案1】:

    当您获得用户的位置时,您并没有更新地图的当前位置。您需要执行以下操作:

    // property to store map view instead of just a local variable in loadView()
    var mapView: GMSMapView?
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //i think this is the problem area
        let userLocation = locations.last!
        long = userLocation.coordinate.longitude
        lat = userLocation.coordinate.latitude
    
        let newCamera = GMSCameraPosition.camera(withLatitude: lat, longitude: long)
        mapView.camera = newCamera
        self.locationManager.stopUpdatingLocation()
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多