我试图显示MKPointAnnotation和用户当前位置之间的路线,但失败了。
我的想法是:获取用户的当前位置-〉获取MKPointAnnotation的坐标-〉与MKPolylineRenderer对齐
问题是我找不到问题所在。:(我不知道应该在哪里修改。
class MapInSearch: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var destination: MKMapItem?
var coords: CLLocationCoordinate2D?
let locationManager = CLLocationManager()
var PlaceLat = ""
var PlaceLong = ""// get from previous view controller
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}// step 1
self.mapView.showsUserLocation = true
self.mapView.delegate = self
self.addRoute() // step 2
}
func addRoute() {
var pointsToUse: [CLLocationCoordinate2D] = []
if PlaceLat != "" || PlaceLong != "" {
let coords = "\(PlaceLat), \(PlaceLong)"
let p = CGPointFromString(coords)
pointsToUse += [CLLocationCoordinate2DMake(CLLocationDegrees(p.x), CLLocationDegrees(p.y))]
}
pointsToUse += [CLLocationCoordinate2DMake(CLLocationDegrees(coords!.latitude), CLLocationDegrees(coords!.longitude))]
let myPolyline = MKPolyline(coordinates: &pointsToUse, count: 2)
mapView.addOverlay(myPolyline)
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let lineView = MKPolylineRenderer(overlay: overlay)
lineView.strokeColor = UIColor.greenColor()
return lineView // step 3
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.coords = manager.location!.coordinate
print("locations = \(coords!.latitude) \(coords!.longitude)")
}
我的代码很乱,因为我混合了4-5个教程。而且,这些教程是用swift 1.2写的。(我试着把它编辑成swift 2,但我失败了)
2条答案
按热度按时间qgelzfjb1#
你曾经解决过你的问题吗?使用XCode 7.3中Swift 2的最新迭代,在你的视图中(我们将称之为MyViewController):
然后在同一文件中:
你可能会发现重要的部分是扩展。我还没有测试过这段代码,所以请随时纠正任何悄悄出现的问题。
rqenqsqc2#
在您的
CLLocationManagerDelegate
委托函数didUpdateLocations
中,您可以通过设置self.myLocation = locations[0] as CLLocation
来更新您的位置然后调用
MakeRoute()
--这是我写的一个函数,可以通过开车或步行来制定路线(因此使用self.driveIsSet
)