swift - 从 CLLocationManager (Google Maps API) 获取用户位置的问题

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

我正在开发一个使用 Google Maps API 的 iPhone 应用程序,但我在获取用户的当前位置时遇到了问题,因此 map 会在他们的位置打开。

我现在已经花了几天时间解决了编译器错误,但它仍然不能正常工作。 map 出现了,但只出现在我为 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()

}
}

最佳答案

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

// 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()

}

关于swift - 从 CLLocationManager (Google Maps API) 获取用户位置的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42261936/

相关文章:

cocoa-touch - 如何为 SCNNode 上的自定义属性设置动画?

swift - 如何将私有(private)函数变成辅助函数?

javascript - 谷歌地图不支持API

javascript - Google Maps API 将变量传递到 InfoWindow

iOS 位置管理器比每秒更新一次更频繁

swift - 如何从 CloudKit 中存储的位置反转地理编码纬度和经度? - swift 3

ios - 关于 MKMapView -regionThatFits :? 的 Apple 文档不正确

xcode - 如何在 Xcode 8 中启用可视内存调试器?

JSON 字符 0 周围值无效调试

android - 更改地点自动完成的语言环境