【发布时间】:2018-04-25 00:36:51
【问题描述】:
我是 swift 3 & Xcode 8 的新手,这是我第一次在这里提问。我想在 Mapkit 中设置几个引脚,并且我还想同时在同一个 Mapkit 中添加用户的位置。此外,我希望这个 Mapkit 的中心是一个特定的位置,而不是用户的位置。然而,我遇到了一个问题。
我可以在我的 Mapkit 中成功设置这些引脚,但我无法在同一个 Mapkit 中显示用户的位置。如果我尝试将用户的位置设置为此 Mapkit 的中心,我可以成功显示用户的位置。我的代码如下所示。
import UIKit
import MapKit
import CoreLocation
class MapVC: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var MapView: MKMapView!
let manager = CLLocationManager()
func createSpanAndAnnotation() {
let FirstSpan: MKCoordinateSpan = MKCoordinateSpanMake(0.008, 0.008)
let originalLocation:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 24.942653, longitude: 121.368598)
let EdittedRegion:MKCoordinateRegion = MKCoordinateRegion(center: originalLocation, span: FirstSpan)
MapView.setRegion(EdittedRegion, animated: true)
let TemporaryGarbageCanLatitude = showData().garbageCanLatitudeArray
let TemporaryGarbageCanLongtitude = showData().garbageCanLontitudeArray
let TemporaryGarbageCanDiscription = showData().garbageCanDiscription
// 'showdata' is another class to store my data of garbageCans in another file.
for i in 0...TemporaryGarbageCanLatitude.count-1 {
let garbageCanLocation : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: TemporaryGarbageCanLatitude[i], longitude: TemporaryGarbageCanLongtitude[i])
let pin = PinAnnotation(title: "Free Garbage Can", subtitle: TemporaryGarbageCanDiscription[i], coordinate: garbageCanLocation)
MapView.addAnnotation(pin)
}
}
//-------------------------------------<Above code could work successfully>-------------------------------------
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.MapView.showsUserLocation = true
}
func locationManager2() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
//--------------------------------<It seems that Above code could not work successfully>--------------------------------
override func viewDidLoad() {
super.viewDidLoad()
createSpanAndAnnotation()
locationManager2()
}
}
我在 Build Phases 中添加了“CoreLocation.framework”,并且在 info.plist 文件中添加了“Privacy - Location When In Use Usage Description”。我在运行模拟器时也打开了设置中的位置服务。此外,我不住在美国,所以我什至去“模拟器>调试>位置>自定义位置”将我的位置更改为我现在住的地方。
但是,在完成以上所有操作后,我仍然无法成功显示用户的位置。谁能帮我解决这个问题?如果有人能帮助我,我将不胜感激,谢谢!
(我的 Mapkit 屏幕截图在这里,但我模糊了其中的一些机密信息。) simulator screen shot
【问题讨论】:
-
您不需要 MapKit 的位置管理器。只需告诉它显示用户位置,它会自动为您请求它。然后检查
isUserLocationVisible以查看它是否真的存在。然后从 mapView.userLocation 检查用户位置以查看坐标。如果要持续跟踪用户,还可以设置 userTrackingMode。 -
您仍然需要在某些时候使用
CLLocationManager来请求访问用户的位置,但 -
@Brandon 感谢您的指导。我稍后会尝试这些东西。
-
@MichaelHulet 感谢您的指导。我会记住的。
标签: ios swift swift3 mapkit xcode8