我正在尝试创建一个跟踪用户位置的应用,并根据用户的位置创建一条线。我在用户去过的地方创建了一堆注释,但无法弄清楚如何在它们之间创建一条线。我是swift和Xcode的新手,我已经浏览了整个互联网,但找不到任何有用的东西。 Picture of app with annotations following user location
这是我的代码:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView?
//Map
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var lblSpeed: UILabel!
let manager = CLLocationManager()
@IBOutlet weak var lblAltitude: UILabel!
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)
lblAltitude.text = String(format:"%.2f", location.altitude)
lblSpeed.text = String(format:"%.2f", location.speed)
self.map.showsUserLocation = true
var testLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
var annotation = MKPointAnnotation()
annotation.coordinate = testLocation
map.addAnnotation(annotation)
var locationTest = [CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)]
var coordinates = locations.map({(location: CLLocation!) -> CLLocationCoordinate2D in return location.coordinate})
var polyline = MKPolyline(coordinates: &testLocation, count: locations.count)
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
}
答案 0 :(得分:0)
你可以尝试
rendererForOverlay
//你也可能想要缩小以显示所有注释+看到画线
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
//同样{{1}} func必须在类级别而不是在另一个函数
中{{1}}