Search code examples
swiftgoogle-maps-sdk-ios

How can I find a user's location using Google Maps SDK for Swift?


So I am trying to get it so I open the app and it starts off at the user's location. The problem is I am getting "User's location is unknown" in the output box. I have location enabled as seen in the code below, so I am wondering if something else might be causing this issue. Help would be appreciated thanks.

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let camera = GMSCameraPosition.cameraWithLatitude(-33.86,
                                                          longitude: 151.20, zoom: 6)
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        mapView.accessibilityElementsHidden = false
        mapView.myLocationEnabled = true
        self.view = mapView

        if let mylocation = mapView.myLocation {
            print("User's location: \(mylocation)")
        } else {
            print("User's location is unknown")
        }
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView

    }

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


}

Solution

  • Have you tried using CLLocationManager() ?

    Try the tutorial below, this should show you how to get the user's location. This will take you through asking the user for permission to see their location, down to reverse geocoding the location to display the address they are at, using GMSGeocoder()

    [https://www.raywenderlich.com/109888/google-maps-ios-sdk-tutorial][1]

    [1]: Ray Wenderlich

    Hope that helps