Swift 当前用户位置
我是Swift新手,我想在地图上显示用户位置,我添加了Swift 当前用户位置,swift,geolocation,location,Swift,Geolocation,Location,我是Swift新手,我想在地图上显示用户位置,我添加了MKMapView,并添加了一个插座,以下是我的代码: import UIKit import Foundation import MapKit import CoreLocation class ViewController: UIViewController ,CLLocationManagerDelegate{ @IBOutlet weak var map: MKMapView! let manager = CLLo
MKMapView
,并添加了一个插座,以下是我的代码:
import UIKit
import Foundation
import MapKit
import CoreLocation
class ViewController: UIViewController ,CLLocationManagerDelegate{
@IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01,0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
但当我在模拟器上运行应用程序时,它会显示美国的其他一些位置。但我来自另一个甚至不靠近美国的地方。因为模拟器使用假位置进行测试。您还可以更改该位置,请参见图像()。
如果您在实际设备上运行,它会显示您当前的位置。您的代码很好,这是因为您在模拟器上运行它,选择调试-->模拟位置-->选择其他位置,您将在屏幕上看到该位置。您在计算机上的模拟器上运行它吗?如果您在实际设备上构建应用程序,则代码是正确的。但您需要为模拟器设置位置。在simulator顶部菜单中,选择Debug,然后查找Location部分并设置自定义location@HastiRanjkesh好的,谢谢