首页 > 解决方案 > 在swift 5中获取位置

问题描述

我意识到还有很多其他页面试图解决CLLocationManager()在 ios swift 中使用获取用户位置的挑战,但它们对我不起作用,这就是我创建这个问题的原因。我的代码在下面,我相信它正确地实现了CLLocationManagerDelegate但调用locationManager.startUpdatingLocation()从不调用该locationManager函数。这使得谷歌地图简单地打开到一个随机位置。我已经模拟了计划中的某些位置,它们像南非一样工作得很好

具有模拟位置的谷歌地图示例:

但是,当我取消选中模拟时,永远找不到该位置。任何建议或帮助将不胜感激。不确定这是否是我的计算机或代码的问题。

import UIKit
import GoogleMaps

class Map: UIViewController, CLLocationManagerDelegate  {

    var mapView: GMSMapView?
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: GMSCameraPosition.camera(withLatitude: 40.7, longitude: -74.0, zoom: 4.0))
        view = mapView

        if (CLLocationManager.locationServicesEnabled()){
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let center = CLLocationCoordinate2D(latitude: locations.last!.coordinate.latitude, longitude: locations.last!.coordinate.longitude)

        let camera = GMSCameraPosition.camera(withLatitude: center.latitude, longitude: center.longitude, zoom: 4.0);
        self.mapView?.camera = camera
        self.mapView?.isMyLocationEnabled = true

        let marker = GMSMarker(position: center)

        print("Latitude :\(center.latitude)")
        print("Longitude :\(center.longitude)")

        marker.map = self.mapView
        marker.title = "Current Location"

        locationManager.stopUpdatingLocation()
    }

}

标签: iosswiftgoogle-mapscllocationmanager

解决方案


推荐阅读