简体   繁体   中英

Cant get current location (GPS) on google maps ios sdk

My goal is to move the camera a user's current location, but for somehow it keeps showing the general map, I have tried many things but seems like it wont move to the user's current location

Screenshot

在此输入图像描述

Current code

import UIKit
import GoogleMaps


class ParcelViewController: UIViewController, GMSMapViewDelegate {


    @IBOutlet var mapView: GMSMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        mapView.delegate = self
    }

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

}


// Mark: -CLLocationManagerDelegate
extension ParcelViewController: CLLocationManagerDelegate {

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedWhenInUse {
            locationManager.startUpdatingLocation()

            mapView.myLocationEnabled = true
            mapView.settings.myLocationButton = true
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

            locationManager.stopUpdatingLocation()

        }
    }
}

Did you add NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription (in your case it's this one) keys in your .plist file. Because if the alert view asking for authorization is not showing this might be the issue.

Make sure you have imported and registered your GoogleMapsAPI Key properly: This is done in the AppDelegate

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    GMSServices.provideAPIKey("[your key from Google API]")

    return true
}

Afterwards, some where in a load fucntion within a ViewController file:

let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)      
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
self.map.setRegion(region, animated: true)

Just a note: Google Maps API does NOT need a user autherization to use the map, however, CLLLocationManager DOES. On a load you should check to see if the permission is set or not, then go from there.

First you need to setup these basic steps :

Step 1: Import the this into your controller class

import CoreLocation

Step 2: Add this delegate to your class file

class Your_controller: CLLocationManagerDelegate

Step 3: Declare this above for viewed load

var locationManager = CLLocationManager()

Step 4: Add this code to your viewdidload method

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()


if CLLocationManager.locationServicesEnabled() {
  switch (CLLocationManager.authorizationStatus()) {
    case .notDetermined, .restricted, .denied:
      print("No access")
    case .authorizedAlways, .authorizedWhenInUse:
      print("Access")
  }
} else {
  print("Location services are not enabled")
}

Step 5: Add this code below viewdidload method

func showCurrentLocation() {
    mapView.settings.myLocationButton = true
    let locationObj = locationManager.location as! CLLocation
    let coord = locationObj.coordinate
    let lattitude = coord.latitude
    let longitude = coord.longitude
    print(" lat in  updating \(lattitude) ")
    print(" long in  updating \(longitude)")

    let center = CLLocationCoordinate2D(latitude: locationObj.coordinate.latitude, longitude: locationObj.coordinate.longitude)
    let marker = GMSMarker()
    marker.position = center
    marker.title = "current location"
    marker.map = mapView
    let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: lattitude, longitude: longitude, zoom: Float(zoomLevel))
    self.mapView.animate(to: camera)

}

Step 6: add to permission your plist file

Key - "Privacy - Location When In Use Usage Description"

Value - "This app needs access to your location"

Step 7: run your Application on Hardware Device

Step 8: Just call the this method when you want to show current location.

self.showCurrentLocation()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM