获取用户当前位置/坐标

235

我该如何存储用户的当前位置并在地图上显示该位置?

我能够在地图上显示预定义的坐标,但我不知道如何从设备接收信息。

此外,我知道我必须将一些项添加到Plist中。我该如何做到这一点?

16个回答

10
 override func viewDidLoad() {

    super.viewDidLoad()       
    locationManager.requestWhenInUseAuthorization();     
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }
    else{
        print("Location service disabled");
    }
  }

这是您的视图加载方法,还应在ViewController类中包括mapStart更新方法,如下所示。

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var locValue : CLLocationCoordinate2D = manager.location.coordinate;
    let span2 = MKCoordinateSpanMake(1, 1)    
    let long = locValue.longitude;
    let lat = locValue.latitude;
    print(long);
    print(lat);        
    let loadlocation = CLLocationCoordinate2D(
                    latitude: lat, longitude: long            

   )     

    mapView.centerCoordinate = loadlocation;
    locationManager.stopUpdatingLocation();
}

不要忘记在项目中添加CoreLocation.Framework和MapKit.Framework(自XCode 7.2.1起不再需要)


5
import Foundation
import CoreLocation

enum Result<T> {
  case success(T)
  case failure(Error)
}

final class LocationService: NSObject {
    private let manager: CLLocationManager

    init(manager: CLLocationManager = .init()) {
        self.manager = manager
        super.init()
        manager.delegate = self
    }

    var newLocation: ((Result<CLLocation>) -> Void)?
    var didChangeStatus: ((Bool) -> Void)?

    var status: CLAuthorizationStatus {
        return CLLocationManager.authorizationStatus()
    }

    func requestLocationAuthorization() {
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            manager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }

    func getLocation() {
        manager.requestLocation()
    }

    deinit {
        manager.stopUpdatingLocation()
    }

}

 extension LocationService: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        newLocation?(.failure(error))
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
            newLocation?(.success(location))
        }
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined, .restricted, .denied:
            didChangeStatus?(false)
        default:
            didChangeStatus?(true)
        }
    }
}

需要在所需的ViewController中编写此代码。

 //NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription


let locationService = LocationService()

 @IBAction func action_AllowButtonTapped(_ sender: Any) {
     didTapAllow()
 }

 func didTapAllow() {
     locationService.requestLocationAuthorization()
 }

 func getCurrentLocationCoordinates(){
   locationService.newLocation = {result in
     switch result {
      case .success(let location):
      print(location.coordinate.latitude, location.coordinate.longitude)
      case .failure(let error):
      assertionFailure("Error getting the users location \(error)")
   }
  }
}

func getCurrentLocationCoordinates() {
    locationService.newLocation = { result in
        switch result {
        case .success(let location):
            print(location.coordinate.latitude, location.coordinate.longitude)
            CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                    return
                }
                if (placemarks?.count)! > 0 {
                    print("placemarks", placemarks!)
                    let pmark = placemarks?[0]
                    self.displayLocationInfo(pmark)
                } else {
                    print("Problem with the data received from geocoder")
                }
            })
        case .failure(let error):
            assertionFailure("Error getting the users location \(error)")
        }
    }
}

这是一个好的方法。 - Chandan Jee

2

所有之前的答案都没有正确地按照正确的步骤进行。在设置CLLocationManager时,您不需要最初调用CLLocationManager.locationServicesEnabled()locationManager.requestWhenInUseAuthorization()。并且在验证您是否有授权之前,不应该调用startUpdatingLocation()

要开始,请添加所需的隐私设置(如果尚未完成)。选择您的应用程序目标并转到“信息”选项卡。在“自定义iOS目标属性”部分下右键单击并选择“添加行”。向下滚动到“隐私”条目,然后选择以下任一项:

  • “使用应用程序期间位置权限说明”
  • “始终允许访问位置权限说明”
  • “始终和使用应用程序期间位置权限说明”

根据您的应用程序需求选择相应的选项。对于值,请确保输入一个句子,解释为用户为什么您的应用程序需要访问他们的位置。如果给定的描述对用户没有用处,则可能会导致您的应用被苹果拒绝。

然后,使用以下(详细注释的)代码作为在视图控制器中获取用户位置的示例:

import UIKit
import CoreLocation

class ViewController: UIViewController {
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Setup the location manager
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation // Or other desired accuracy

        // That's it for the initial setup. Everything else is handled in the
        // locationManagerDidChangeAuthorization delegate method.
    }
}

extension ViewController: CLLocationManagerDelegate {
    // This is called as soon as the location manager is setup (in viewDidLoad)
    // This is called when the user responds to the privacy dialog
    // This is called if the user changes the privacy setting in the Settings app
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .notDetermined:
            // Request the appropriate authorization based on the needs of the app
            manager.requestWhenInUseAuthorization()
            // manager.requestAlwaysAuthorization()
        case .restricted:
            print("Sorry, restricted")
            // Optional: Offer to take user to app's settings screen
        case .denied:
            print("Sorry, denied")
            // Optional: Offer to take user to app's settings screen
        case .authorizedAlways, .authorizedWhenInUse:
            // The app has permission so start getting location updates
            manager.startUpdatingLocation()
        @unknown default:
            print("Unknown status")
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Received \(locations.count) locations")

        // Some location updates can be invalid or have insufficient accuracy.
        // Find the first location that has sufficient horizontal accuracy.
        // If the manager's desiredAccuracy is one of kCLLocationAccuracyNearestTenMeters,
        // kCLLocationAccuracyHundredMeters, kCLLocationAccuracyKilometer, or kCLLocationAccuracyThreeKilometers
        // then you can use $0.horizontalAccuracy <= manager.desiredAccuracy. Otherwise enter the number of meters desired.
        if let location = locations.first(where: { $0.horizontalAccuracy <= 40 }) {
            print("Good location found: \(location)")
            // Call the following if you don't need any more updates
            manager.stopUpdatingLocation()

            // Do something useful with the found location
            // - show on a map
            // - Reverse geocode to get the address
            // - send to server
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location manager error: \(error)")
    }
}

2
这是一个我测试过可用的复制粘贴示例。

http://swiftdeveloperblog.com/code-examples/determine-users-current-location-example-in-swift/

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager:CLLocationManager!

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

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

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        determineMyCurrentLocation()
    }


    func determineMyCurrentLocation() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation

        // Call stopUpdatingLocation() to stop listening for location updates,
        // other wise this function will be called every time when user location changes.

       // manager.stopUpdatingLocation()

        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Error \(error)")
    }
}

-1
// its with strongboard 
@IBOutlet weak var mapView: MKMapView!

//12.9767415,77.6903967 - exact location latitude n longitude location 
let cooridinate = CLLocationCoordinate2D(latitude: 12.9767415 , longitude: 77.6903967)
let  spanDegree = MKCoordinateSpan(latitudeDelta: 0.2,longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: cooridinate , span: spanDegree)
mapView.setRegion(region, animated: true)

-1

在iOS Swift 4中百分百有效,作者:Parmar Sajjad

步骤1:前往Google开发者API控制台并创建您的ApiKey

步骤2:前往项目安装Cocoapods GoogleMaps pod

步骤3:前往AppDelegate.swift,导入GoogleMaps和

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    GMSServices.provideAPIKey("ApiKey")
    return true
}

第四步: 导入UIKit 导入GoogleMaps class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapview: UIView!
let locationManager  = CLLocationManager()

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

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


func locationManagerSetting() {

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    self.showCurrentLocationonMap()
    self.locationManager.stopUpdatingLocation()
}
func showCurrentLocationonMap() {
    let
    cameraposition  = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)!  , longitude: (self.locationManager.location?.coordinate.longitude)!, zoom: 18)
    let  mapviewposition = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: self.mapview.frame.size.width, height: self.mapview.frame.size.height), camera: cameraposition)
    mapviewposition.settings.myLocationButton = true
    mapviewposition.isMyLocationEnabled = true

    let marker = GMSMarker()
    marker.position = cameraposition.target
    marker.snippet = "Macczeb Technologies"
    marker.appearAnimation = GMSMarkerAnimation.pop
    marker.map = mapviewposition
    self.mapview.addSubview(mapviewposition)

}

}

步骤5:打开info.plist文件,在隐私-位置时使用说明下方添加以下内容......在主故事板文件基本名称下方

步骤6:运行


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接