我是Swift的新手,我想在地图上显示用户位置,我添加了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.
}
}
但是,当我在模拟器上运行该应用程序时,它会向我显示美国的其他位置。但是我来自另一个距离美国不远的地方。
答案 0 :(得分:1)
因为模拟器将虚假位置用于测试目的。您还可以更改该位置。请参见图像(https://i.stack.imgur.com/2GN7x.png)。 如果您在实际设备上运行,它将显示您的当前位置。
答案 1 :(得分:1)
您的代码很好,这是因为您在模拟器上运行它,然后选择“调试”->“模拟位置”->选择其他位置,然后您会在屏幕上看到该位置