I'm working on an iPhone app that uses the Google Maps API, and I'm having issues getting the current location of the user, so that the map opens on their location.
I've spent a few days on it now and have gotten rid of compiler errors, but it's still not working quite right. The map shows up, but only at the initial coordinates I provide for the long and lat variables. I think it has something to do with the CLLoationManager()
.
Updating the location on the simulator yields no results, and I feel like I'm making a rookie mistake, I just don't know what. And suggestions?
import UIKit
import CoreLocation
import GoogleMaps
class ViewController: UIViewController, CLLocationManagerDelegate {
var long:Double = -0.13
var lat:Double = 51.0
let locationManager = CLLocationManager()
override func loadView() {
// Create a GMSCameraPosition that tells the map to display the
//user location stuff
self.locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let camera = GMSCameraPosition.camera(withLatitude: CLLocationDegrees(lat), longitude: CLLocationDegrees(long), zoom: 5.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
mapView.showUserLocation = true
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 51.51 , longitude: -0.13)
marker.title = "Test"
marker.snippet = "This is a test"
marker.map = mapView
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //i think this is the problem area
let userLocation = locations.last!
long = userLocation.coordinate.longitude
lat = userLocation.coordinate.latitude
self.locationManager.stopUpdatingLocation()
}
}
When you get the user's location, you're not updating the current location of the map. You need to do something like:
// property to store map view instead of just a local variable in loadView()
var mapView: GMSMapView?
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //i think this is the problem area
let userLocation = locations.last!
long = userLocation.coordinate.longitude
lat = userLocation.coordinate.latitude
let newCamera = GMSCameraPosition.camera(withLatitude: lat, longitude: long)
mapView.camera = newCamera
self.locationManager.stopUpdatingLocation()
}