I trying to record a path user is taking using GoogleMap SDK. I'm using polyline to draw line on a map to show user the path that is taken. In an attempt to cut down coordinates that is generated and to make line looks clean(instead of looking squiggly), I'm calling startMonitoringSignificantChange of CLLocationManger instead of startUpdatingLocation. However, that does not seem to work. It calls didUpdateLocations method just once when the view is loaded, but after that, it just stops calling. Where am I doing wrong?
This is my code
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestAlwaysAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
}
extension LocationViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways {
locationManager.startMonitoringSignificantLocationChanges()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = manager.location {
path.addCoordinate(CLLocationCoordinate2D(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude))
let polyline = GMSPolyline(path: path)
polyline.strokeColor = UIColor.redColor()
polyline.strokeWidth = 3
polyline.geodesic = true
polyline.map = mapView
// Save the coordinates to array
coordinateArray.append([location.coordinate.latitude, location.coordinate.longitude])
}
}
}
}
Add following lines of codes after locationManager.requestAlwaysAuthorization()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
p.s. If your view is holding locationManager instance, it may not receive location-updates after your view is un-loaded. You may remove following line as it is useless for significant-location-updates:
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
Related
I am trying to display the current location of the user and have the region set to their current location.
Here is my code.
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let userLocation = locations.last
let viewRegion = MKCoordinateRegionMakeWithDistance((userLocation?.coordinate)!, 600, 600)
self.mapView.setRegion(viewRegion, animated: true)
}
What happens:
Map loads
Map region is set to current location
Map region will keep updating to the current location
Current location gets printed to the console
What doesn't work:
"Blue" current location indicator does not appear.
If you know what I need to do to make the "Blue" current location indicator appear it will be much appreciated.
You need to set
mapView.showsUserLocation = true
In viewDidLoad
I am using this code for set current location in center on map
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
mapView.positionIndicator.visible = true
mapView.positionIndicator.accuracyIndicatorColor = UIColor.greenColor()
mapView.positionIndicator.accuracyIndicatorVisible = true
mapView.zoomLevel = 13.2
let currentGeoPosition=NMAPositioningManager.sharedPositioningManager().currentPosition
mapView.setGeoCenter(currentGeoPosition.coordinates, withAnimation: .Bow)
But I got error unexpectedly found nil while unwrapping an Optional value.
please tell me how do I get current location on center
you can get current position (lat,long) by this:
import CoreLocation
let locationManger = CLLocationManager()
locationManger.delegate = self
locationManger.desiredAccuracy = kCLLocationAccuracyBest
locationManger.requestWhenInUseAuthorization()
locationManger.startUpdatingLocation()
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print (locations)
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
let lat = String(locValue.latitude)
let lang = String(locValue.longitude)
}
I want to save a set of latitude and longitude coordinates to Firebase, but whenever my app runs through this code it crashes!
let userID: String = (FIRAuth.auth()?.currentUser?.uid)!
let lat: Double = (locationManager.location?.coordinate.latitude)!
let lon: Double = (locationManager.location?.coordinate.longitude)!
self.ref.child("Location").child(userID).setValue(["Latitude": lat, "Longitude": lon])
Is there anyway I can fix this and save it properly and efficiently?
Make sure of two things :-
1.) your viewController inherits from CLLocationManagerDelegate and has its delegate set to self in viewDidLoad
2.) your info.plist has these keys added to them :-
NSLocationAlwaysUsageDescription --- I need Location
NSLocationWhenInUseUsageDescription --- I need Location
privacy - location usage description --- I need Location
class MapViewController: UIViewController , CLLocationManagerDelegate...{
...
..
let locationManager = CLLocationManager()
func viewDidLoad(){
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.startUpdatingLocation()
}
//Call these functions for updating the getting the values of current location
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
print("authorised call came . . . . ")
mapView.myLocationEnabled = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print("target position : = \(location.coordinate)")
print(locationManager.location!.coordinate.latitude)
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
self.FIRDatabase.database().reference().child("Location").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Latitude": locationManager.location!.coordinate.latitude, "Longitude": locationManager.location!.coordinate.longitude])
}
}
}
I've got this code:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
and this code:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations.last
print(userLocation)
let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude,
longitude: userLocation!.coordinate.longitude, zoom: 12.5)
self.mapView.camera = camera
self.mapView.myLocationEnabled = true
// self.mapView.settings.myLocationButton = true
locationManager.stopUpdatingLocation()
}
This was working earlier but now it seems like locationManager isn't even being called as the print statement isn't returning any information at all. There are no errors in the code and I can't seem to figure out why the function isn't being called. Can anyone spot anything obvious that I'm missing?
Thank you
I just implemented this and I'm going to say you what I've done
First, you create a locationManager variable
let locationManager: CLLocationManager = CLLocationManager()
You have to request permission in the viewDidLoad()
viewMap.delegate = self
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
Then, I created an extension and I implemented the delegate
extension MyView: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
//here you configure the locationManager
locationManager.startUpdatingLocation()
viewMap.isMyLocationEnabled = true
viewMap.settings.myLocationButton = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
}
I hope this help you, here works properly.
This question already has answers here:
Get User's Current Location / Coordinates
(16 answers)
Closed 6 years ago.
I am trying to get the long and lat of my users locations, I have done the following:
imported Core Location
import CoreLocation
Add Core Location Delegate
class ViewController: UIViewController, CLLocationManagerDelegate, AVCaptureMetadataOutputObjectsDelegate, DTDeviceDelegate {
defined this variable:
var locationManager: CLLocationManager!
and then added this method:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
print(long, lat)
//Do What ever you want with it
}
but the location does not get printed, my method does not even get it.
I add the items to use Core Location to my plist and the app ask me to use the location services when I first run it. But now location is getting printed....what am I doing wrong?
Maybe you forgot to set value for the delegate
In your viewDidLoad() add this:
if CLLocationManager.locationServicesEnabled() {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
}
Use this Code,
declare locationManager
var locationManager = CLLocationManager()
Set the Delegate in viewDidLoad, shown below code,
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .NotDetermined {
self. locationManager.requestWhenInUseAuthorization()
}
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
Add this in viewdidload,
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8)
{
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
else
{
#if debug
println("Location services are not enabled");
#endif
}
Then add this two delegate method to get location,
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
locationManager.stopUpdatingLocation()
if ((error) != nil)
{
print(error)
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as! CLLocation
var coord = locationObj.coordinate
print(coord.latitude)
print(coord.longitude)
}
This way you will get your current location.
You neeed to initialize the locationManageger and enable the location flag in xcode also, it appaear bottom of the xcode
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOS 8.0, *) {
if Bundle.main.infoDictionary?["NSLocationAlwaysUsageDescription"] != nil {
self.locationManager.requestAlwaysAuthorization()
}
else {
self.locationManager.requestWhenInUseAuthorization()
}
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
You can add this code to your viewDidLoad() method:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
This will call the locationManagers didUpdate delegate-methods if location services are available for your app