如何使用 Google Maps SDK for Swift 查找用户的位置?

How can I find a user's location using Google Maps SDK for Swift?

所以我试图获取它,所以我打开应用程序,它从用户所在的位置开始。问题是我在输出框中得到 "User's location is unknown" 。我已启用位置,如下面的代码所示,所以我想知道是否有其他原因导致此问题。帮助将不胜感激。

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let camera = GMSCameraPosition.cameraWithLatitude(-33.86,
                                                          longitude: 151.20, zoom: 6)
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        mapView.accessibilityElementsHidden = false
        mapView.myLocationEnabled = true
        self.view = mapView

        if let mylocation = mapView.myLocation {
            print("User's location: \(mylocation)")
        } else {
            print("User's location is unknown")
        }
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

您尝试过使用 CLLocationManager() 吗?

试试下面的教程,它应该会告诉您如何获取用户的位置。这将带您通过询问用户是否允许查看他们的位置,使用 GMSGeocoder()

对位置进行反向地理编码以显示他们所在的地址

[https://www.raywenderlich.com/109888/google-maps-ios-sdk-tutorial][1]

[1]:雷·温德利希

希望对您有所帮助

我这样试过:

  1. "Privacy - Location When In Use Usage Description"(或简单地NSLocationWhenInUseUsageDescription) 我的 Info.plist 属性文件。然后这将要求您授权查找您的位置。

  2. 在您的视图中设置正确的委托 (GMSMapViewDelegate):例如

    class 地图视图:UIViewController、GMSMapViewDelegate{...}

  3. 最后将委托设置为您的 GMSMapView 实例。在我的例子中 mapView:

let mapView = GMSMapView.map(withFrame: frameMapViewContainer, camera: camera) mapView.delegate = self