【发布时间】:2016-02-28 16:19:43
【问题描述】:
我正在编写一个应用程序,并且我有一个嵌入式地图视图来显示用户的位置。到目前为止,这是我的代码:
class YourCurrentLocation: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 1000
func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
mapView.showsUserLocation = true
centerMapOnLocation(locationManager.location!, map: mapView, radius: regionRadius)
} else {
locationManager.requestAlwaysAuthorization() //requestWhenInUseAuthorization()
}
}
func centerMapOnLocation(location: CLLocation, map: MKMapView, radius: CLLocationDistance) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
radius * 2.0, radius * 2.0)
map.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// mapView.delegate = self
if CLLocationManager.locationServicesEnabled()
{
//locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
print("location enabled")
checkLocationAuthorizationStatus()
}
else
{
print("Location service disabled");
}
// Do any additional setup after loading the view.
}
}
我还将这两个条目添加到我的 plist 中:
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
在我的 xcode 中,我已经设置模拟英国伦敦的 GPS 数据。
当我运行应用程序时 - 我看到了地图,但没有标记伦敦。我做错了什么?
顺便说一句,我不得不注释掉这一行:
//mapView.delegate = self
在viewDidLoad(),否则我有错误:
Cannot assign value of type YourCurrentLocation to type MKMapViewDelegate
我不确定这是否是问题的一部分。
我想实现当我向用户显示地图以及在该地图上标有他的位置的点时的效果。你能帮我解决这个问题吗?
【问题讨论】:
-
locationManager.location!在您的代码中将为您提供模拟器或设备的最后位置,可以是任何东西。在我的回答中,我将向您展示如何使用CLLocationManagerDelegate来获取实际的用户位置。 -
好的,我明白了...谢谢!最后一个问题 - 如果手机不在 GPS 范围内或该位置尚未与真实位置区分开来,会发生什么情况?
-
@user3766930 如果确实解决了您的问题,您可以将答案标记为已接受。
标签: ios swift mkmapview mapkit