简体   繁体   English

如何停止获取用户在MapBox中的位置

[英]How to Stop getting the users location in MapBox

How can you stop getting the user location when using CLLocationManager and mapbox ? 使用CLLocationManagermapbox时如何停止获取用户位置?

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. 1)使用CLLocationManager获取用户的当前位置,然后调用命令“ .stopUpdatingLocation() ”,该命令停止获取用户位置。
2) Creates a map with mapbox 2)使用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. 我在各个单独的场景(单独的上述选项1和单独的选项2)中测试了该应用程序,它成功停止获取用户位置,但是当应用程序都实现时,它并没有停止获取用户位置。

viewController.swift: 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 AppDelegate.swift:导入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: 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
    }
}

您正在调用function返回的manager ,请尝试调用self.manager.stopUpdatingLocation()

Resolved this issue by getting the user location inside the "ViewDidLoad" method and creating the map inside the "ViewDidAppear" method 通过获取“的viewDidLoad”方法中,用户的位置,创造了“ViewDidAppear”方法里面的地图解决这个问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM