迅速找到位置5

时间:2019-04-20 19:37:57

标签: ios swift google-maps cllocationmanager

我意识到还有很多其他页面试图解决在iOS Swift中使用CLLocationManager()获取用户位置的挑战,但是它们对我不起作用,这就是为什么我创建了这个问题。我认为下面的代码可以正确实现CLLocationManagerDelegate,但是对locationManager.startUpdatingLocation()的调用从不调用locationManager函数。这使得Google Map可以简单地打开到任意位置。我已经模拟了该方案中的某些位置,它们像南非一样运作良好

带有模拟位置的Google Map示例:

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

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

}

0 个答案:

没有答案