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

我可以在地图上显示预定义的坐标,只是不知道如何从设备接收信息。

我也知道我必须添加一些项目到Plist。我该怎么做呢?


当前回答

NSLocationWhenInUseUsageDescription =请求权限使用位置服务时,应用程序是在后台。在你的plist文件中。

如果这是工作,然后请投票的答案。

其他回答

 override func viewDidLoad() {

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

这是你的视图didload方法,在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。框架和MapKit。项目中的框架(从XCode 7.2.1开始不再需要)

首先在项目中添加两个框架

1:地

2:共重定位(从XCode 7.2.1开始不再需要)

在类中定义

var manager:CLLocationManager!
var myLocations: [CLLocation] = []

然后在viewDidLoad方法中编写此代码

manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()

//Setup our Map View
mapobj.showsUserLocation = true

不要忘记在plist文件中添加这两个值

1: NSLocationWhenInUseUsageDescription

2: NSLocationAlwaysUsageDescription

像这样导入库:

import CoreLocation

设置委托:

CLLocationManagerDelegate

取如下变量:

var locationManager:CLLocationManager!

在viewDidLoad()上写这样漂亮的代码:

 locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

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

编写CLLocation委托方法:

    //MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation :CLLocation = locations[0] as CLLocation

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

    self.labelLat.text = "\(userLocation.coordinate.latitude)"
    self.labelLongi.text = "\(userLocation.coordinate.longitude)"

    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
        }
    }

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

现在设置访问位置的权限,将这些键值添加到您的信息中。plist文件

 <key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

100%工作,没有任何问题。测试

首先导入Corelocation和MapKit库:

import MapKit
import CoreLocation

从CLLocationManagerDelegate继承到我们的类

class ViewController: UIViewController, CLLocationManagerDelegate

创建一个locationManager变量,这将是你的位置数据

var locationManager = CLLocationManager()

创建一个函数来获取位置信息,具体语法如下:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

在函数中为用户的当前位置创建一个常量

let userLocation:CLLocation = locations[0] as CLLocation // note that locations is same as the one in the function declaration  

停止更新位置,这可以防止你的设备在移动时不断地改变窗口以使你的位置居中(如果你想让它发挥其他作用,你可以省略这个)

manager.stopUpdatingLocation()

从刚刚定义的userLocatin获取用户坐标:

let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)

定义你想要缩放的地图:

let span = MKCoordinateSpanMake(0.2,0.2) 将这两个组合起来得到region:

let region = MKCoordinateRegion(center: coordinations, span: span)//this basically tells your map where to look and where from what distance

现在设置区域,并选择是否希望它与动画一起去那里

mapView.setRegion(region, animated: true)

关闭函数 }

从你的按钮或者其他你想要设置locationManagerDeleget为self的方式

现在允许显示位置

指定精度

locationManager.desiredAccuracy = kCLLocationAccuracyBest

授权:

 locationManager.requestWhenInUseAuthorization()

为了能够授权位置服务,您需要将这两行添加到您的plist

位置:

locationManager.startUpdatingLocation()

显示给用户:

mapView.showsUserLocation = true

这是我的完整代码:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!
    
    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.
    }

  
    @IBAction func locateMe(sender: UIBarButtonItem) {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        
        mapView.showsUserLocation = true
        
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation
        
        manager.stopUpdatingLocation()
        
        let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
        let span = MKCoordinateSpanMake(0.2,0.2)
        let region = MKCoordinateRegion(center: coordinations, span: span)
        
        mapView.setRegion(region, animated: true)
        
    }
}

你应该做这些步骤:

add CoreLocation.framework to BuildPhases -> Link Binary With Libraries (no longer necessary as of XCode 7.2.1) import CoreLocation to your class - most likely ViewController.swift add CLLocationManagerDelegate to your class declaration add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to plist init location manager: locationManager = CLLocationManager() locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() get User Location By: func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") }