developer1996
developer1996

Reputation: 894

Current Location using Google Maps and Swift

I need to show my real current location. I used these two tutorials as references: Google Maps SDK iOS and Ray Wenderlich.

Neither helped show me my real current location it shows me Apple's Location.

I added Privacy - Location When In Use Usage Description and LSApplicationQueriesSchemes into my info.plist file.

What is wrong with my code?

How can I added a marker with my current location?

My Code:

AppDelegate.swift

import GoogleMaps
import GooglePlaces
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    GMSServices.provideAPIKey("AIzaSyCNcYUEURD7DSk6qksdKyp63w-ZetdWQZc")
    GMSPlacesClient.provideAPIKey("AIzaSyCNcYUEURD7DSk6qksdKyp63w-ZetdWQZc")
    return true
}

ViewController.swift

import UIKit
import GoogleMaps
import GooglePlaces

class ViewController: UIViewController {

    @IBOutlet weak var mapView: GMSMapView!
    private var locationManager = CLLocationManager()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }
 }

 extension ViewController: CLLocationManagerDelegate {
// 2
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    // 3
    guard status == .authorizedWhenInUse else {
        return
    }
    // 4
    locationManager.startUpdatingLocation()

    //5
    mapView.isMyLocationEnabled = true
    mapView.settings.myLocationButton = true
}

// 6
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.first else {
        return
    }

    // 7
    mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

    // 8
    locationManager.stopUpdatingLocation()
  }
}

Upvotes: 0

Views: 5487

Answers (1)

valosip
valosip

Reputation: 3402

If you're running this in the simulator, you'll get one of the preset locations. You can change simulator location by going to DEBUG > Location > select preset or custom. If you want to set location of simulator to your current location, go to maps.google.com right click on map and select "What's here?" and it will give you the lat/long. Copy and paste those into the "custom location" from above setting.

If you run on an actual device, you'll get devices location, assuming you have asked for all the correct permissions and set the info.plist entries.

Upvotes: 2

Related Questions