How to Stop getting the users location in MapBox

2.2k views Asked by At

How can you stop getting the user location when using CLLocationManager and mapbox?

I have a application that does the following:
1) Gets the users current location with the CLLocationManager and then calls the command ".stopUpdatingLocation()" which stops getting the user location.
2) Creates a map with mapbox
As soon as the application has both, it does NOT stop getting the user location.

I tested the application in the each separate scenarios (option 1 above alone and option 2 alone) and it successfully stop getting the user location but when the application has both implemented it does NOT stop getting the user location.

viewController.swift:

import UIKit
import MapboxGL
import CoreLocation

class ViewController: UIViewController, MGLMapViewDelegate , CLLocationManagerDelegate {

    //MARK: - Properties
    var manager: CLLocationManager?

    private var currentLocation: CLPlacemark?
    private var currLocLatitude:CLLocationDegrees?
    private var currLocLongitude:CLLocationDegrees?
    private var currLocTitle:String?
    private var currLocSubtitle:String?

    private var MapBoxAccessToken = "AccessToken.GoesHere"

    //MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        manager = CLLocationManager()
        manager?.delegate = self
        manager?.desiredAccuracy = kCLLocationAccuracyBest
        manager?.requestWhenInUseAuthorization()
        manager?.startUpdatingLocation()
    }

    //MARK: - Helper        
    /* gather location information */
    func getLocationInfo(placemark: CLPlacemark) {

        currentLocation  =  placemark //will delete later - redudant
        currLocLatitude  =  placemark.location.coordinate.latitude
        currLocLongitude =  placemark.location.coordinate.longitude
        currLocTitle     =  placemark.areasOfInterest[0] as? String
        currLocSubtitle  =  placemark.locality

        //DEBUGGING
        print(placemark.location.coordinate.latitude)
        print(placemark.location.coordinate.longitude)
        print(placemark.areasOfInterest[0])
        print(placemark.locality)
    }

    //MARK: - CLLocationManagerDelegate
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        manager.stopUpdatingLocation()

        let location = locations[0] as? CLLocation
        let geoCoder = CLGeocoder()
        geoCoder.reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error) -> Void in

            if (error != nil) {
                println("ERROR:" + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                var currLocation = placemarks[0] as! CLPlacemark

                self.getLocationInfo(currLocation)
                self.createMapBoxMap()

            } else {
                print("Error with data")
            }
        })
    }

    func locationManager( manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        print(" Authorization status changed to \(status.rawValue)")

    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError) {
        print("Error:" + error.localizedDescription)
    }

    //MARK: - MapBox Methods
    private func createMapBoxMap(){

        //type of map style
        let mapView = MGLMapView(frame: view.bounds, accessToken: MapBoxAccessToken)

        //dark map style
        //  let mapView = MGLMapView(frame: view.bounds, accessToken: "pk.eyJ1IjoibHVvYW5kcmUyOSIsImEiOiI4YzAyOGMwOTAwMmQ4M2U5MTA0YjliMjgxM2RiYzk0NSJ9.isuNZriXdmrh-n9flwTY9g",styleURL: NSURL(string: "asset://styles/dark-v7.json"))

        mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

        //setting the map's center coordinate
        mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: currLocLatitude!, longitude: currLocLongitude!),
            zoomLevel: 25, animated: false)
        view.addSubview(mapView)

        /*define the marker and its coordinates, title, and subtitle:*/
        mapView.delegate = self  // Set the delegate property of our map view to self after instantiating it.

        // Declare the marker `ellipse` and set its coordinates, title, and subtitle
        let ellipse = MyAnnotation(location: CLLocationCoordinate2D(latitude: currLocLatitude!, longitude: currLocLongitude!),
            title: currLocTitle!, subtitle: currLocSubtitle!)

        mapView.addAnnotation(ellipse) // Add marker `ellipse` to the map
    }


    //MARK: - MGLMapViewDelegate
    /* defining the marker from MyAnnotation.swift */
    func mapView(mapView: MGLMapView!, symbolNameForAnnotation annotation: MGLAnnotation!) -> String! {
        return "secondary_marker"
    }

    /* Tapping the marker */
    func mapView(mapView: MGLMapView!, annotationCanShowCallout annotation: MGLAnnotation!) -> Bool {
        return true
    }
}

AppDelegate.swift: import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

}

MyAnnotation.swift:

import Foundation
import MapboxGL

class MyAnnotation: NSObject, MGLAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String!
    var subtitle: String!

    init(location coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
}
2

There are 2 answers

4
Icaro On

You are calling the manager returned in the function, try call self.manager.stopUpdatingLocation()

0
LuAndre On

Resolved this issue by getting the user location inside the "ViewDidLoad" method and creating the map inside the "ViewDidAppear" method

By having them seperated, it seems to have resolve the problem.

 import UIKit
 import CoreLocation
 import MapboxGL

class AViewController: UIViewController, CLLocationManagerDelegate {

var manager:CLLocationManager!
var userLocation:CLLocation!

override func viewDidLoad() {
    super.viewDidLoad()

    getUserLocation()
}//eom

override func viewDidAppear(animated: Bool) {
    createMapBoxMap()
}

    /*getting user current location*/
    func getUserLocation(){
        self.manager = CLLocationManager()
        self.manager.delegate = self
        self.manager.desiredAccuracy = kCLLocationAccuracyBest
        self.manager.requestWhenInUseAuthorization()
        self.manager.startUpdatingLocation()
    }//eom

    /*location manager 'didUpdateLocations' function */
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        self.manager.stopUpdatingLocation() //stop getting user location
        println(locations)
        self.userLocation = locations[0] as! CLLocation
    }//eom

    /*Create preliminary map */
    func createMapBoxMap(){

        // set your access token
        let mapView = MGLMapView(frame: view.bounds, accessToken: "pk.eyJ1IjoiZGFya2ZhZGVyIiwiYSI6IlplVDhfR3MifQ.pPEz732qS8g0WEScdItakg")

        mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

        // set the map's center coordinate
        mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: self.userLocation.coordinate.latitude, longitude: self.userLocation.coordinate.longitude),
            zoomLevel: 13, animated: false)
        view.addSubview(mapView)

        //showing the user location on map - blue dot
        mapView.showsUserLocation = true
    }//eom