Current location in not working in Google Map

前端 未结 2 1542
星月不相逢
星月不相逢 2021-02-03 15:55

I have integrated google map in swift 3, when map screen appear than current location in not showing, i have added two keys in .plist file and also set CLLocationManager delegat

相关标签:
2条回答
  • 2021-02-03 16:32

    For showing current location we don't need any location manager in case of GoogleMaps. All we need is to add one of the keys or both in the .plist. So make sure the key is there. I have used NSLocationWhenInUseUsageDescription key.

    <key>NSLocationWhenInUseUsageDescription</key>
        <string>Allow location</string>
    

    Also make sure that you have called GMSServices provideAPIKey method and replaced with the API_KEY you generated in google developer console. Also all the relevant Google APIs as per requirement should be enabled.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
           // Override point for customization after application launch.
           GMSServices.provideAPIKey("YOUR_API_KEY")
           return true
        }
    

    So, I am assuming you have done all the settings and things right in google developer console.

    By just writing the below line in your controller where you have made the GoogleMap can show the location allow/disallow prompt and take the permission of the user.

    mapView.isMyLocationEnabled = true
    

    However this will not animate your map to your current location. But you can manually drag the map to check the current location and you will see a blue dot at your current location.

    But now we also want to animate to the current location whenever we load that ViewController. Now the need for CLLocationManager arrives. So that in its didUpdateLocation delegate, we can fetch the current location and can just animate the graph to the current location.

    So here is my complete controller.

    import UIKit
    import GoogleMaps
    
    class ViewController: UIViewController,GMSMapViewDelegate,CLLocationManagerDelegate {
        @IBOutlet weak var mapView: GMSMapView!
    
        var locationManager = CLLocationManager()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            mapView.isMyLocationEnabled = true
            mapView.delegate = self
    
            //Location Manager code to fetch current location
            self.locationManager.delegate = self
            self.locationManager.startUpdatingLocation()
        }
    
        //Location Manager delegates
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
            let location = locations.last
    
            let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:14)
            mapView.animate(to: camera)
    
            //Finally stop updating location otherwise it will come again and again in this delegate
            self.locationManager.stopUpdatingLocation()
    
        }
    }
    

    Another way of doing is not using the didUpdateLocation and not using the location manager is just by using the GMSMapViewDelegate delegate method mapViewDidFinishTileRendering

    func mapViewDidFinishTileRendering(_ mapView: GMSMapView) {
        let location = mapView.myLocation
        let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:14)
        mapView.animate(to: camera)
    }
    

    It will be called everytime the map rendering is finished.
    But this comes with a limitation, it will always bring you to the current location whenever you drag/pinch/zoom map as the rendering finish everytime you play with map. So, you can just implement some kind of bool variable logic here.

    You can get your location by using

    let yourCurrentLocation = mapView.myLocation
    

    Make sure to do this on a device rather than simulator. If you are using simulator, you have to choose some custom location and then only you will be able to see the blue dot.

    I already gave this type of answer. Check this Link. But that was in Swift 2.x. The one which I posted in this answer is in Swift 3.x

    0 讨论(0)
  • 2021-02-03 16:35

    This is a bit detailed, so I'd like to leave it in a full answer. This is the most common reason I have encountered for a nil location, since figuring out the basics, a few years ago. So, you call CLLocationManager.startLocating(), in your viewDidLoad. Then you call the method that sets up your map. Sometimes this works, and sometimes it doesn't, because of a race condition caused by the amount of time it takes the CLLocationManager to set up permissions, on the one hand, and access the user's location, in another part of the code. Let's look at an order of events, where it doesn't work:

    1) you call requestAlwaysAuthroization and startLocating 2) User permissions setup is triggered on one thread 3) In your ViewController, you request the user's location, to set up your map 4) It comes back nil 5) NOW, step 2 finishes, and the app has access to the user's location, but it's too late

    The core problem, is that the process that starts with requesting permissions and location, takes more than a few milliseconds. And if your view is already set up, it takes few milliseconds for it to go through the methods in your viewDidLoad. By the time you have the location you need, you've already requested it. This has caused me too many crashes, in my location-based apps.

    My workaround, has been to craft a singleton CLLocationManager, make my starting view a delegate, and requestAlwaysAuthorization and startLocating, in that view. That way, when I get to the view that needs the location, the app has already started locating, and the locationManager.location is not nil.

    This is an approach that will obviously not work for every app. If you need clarification, let me know, and if you need code, as well. I have a few public iO git repos, with projects where I have encountered and fixed this problem.

    0 讨论(0)
提交回复
热议问题