У меня проблема с моими картами.Я установил showsUserLocation
и сделал startUpdatingLocation()
.Мигающая синяя точка появляется, но она никогда не двигается.Если я закрою экран и снова открою, синяя точка переместится на новое место, но она просто статична на карте.Вызывается обратный вызов на didUpdateLocations
, и я могу подобрать текущее местоположение и нарисовать линию точного поиска пути.Я просто не могу заставить синюю точку двигаться вместе с пользователем.Насколько я понимаю, синяя точка перемещалась «сама по себе», пока местоположение обновляется.Что я пропустил?
Вот краткий обзор кода:
import MapKit
import CoreLocation
class AppointmentDetailViewController: UIViewController, UINavigationControllerDelegate, CLLocationManagerDelegate, MKMapViewDelegate {
...
override func viewDidLoad() {
super.viewDidLoad()
firstTime = true
self.mapView?.delegate = self
locationManager = CLLocationManager()
// Ask for Authorisation from the User.
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
self.mapView!.showsUserLocation = true
mapView.showAnnotations(mapView.annotations, animated: true)
} else {
print("Location service disabled", terminator: "")
}
}
override func viewWillAppear(_ animated: Bool) {
firstTime = true
locationManager.startUpdatingLocation()
}
override func viewWillDisappear(_ animated: Bool) {
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Location updated...")
if firstTime {
if appointment == nil { return }
firstTime = false
var latitude:Double = 0
var longitude:Double = 0
if appointment.latitude != nil {
latitude = (appointment.latitude! as NSString).doubleValue
}
if appointment.longitude != nil {
longitude = (appointment.longitude! as NSString).doubleValue
}
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: false)
mapView.showsUserLocation = true
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = appointment.providerFirstName! + " " + appointment.providerLastName!
annotation.subtitle = appointment.address1
mapView.addAnnotation(annotation)
// mapView.selectAnnotation(annotation, animated: true)
// Get directions and draw route line
let point1 = MKPointAnnotation()
let point2 = MKPointAnnotation()
myLatitude = (locations.first?.coordinate.latitude)!
myLongitude = (locations.first?.coordinate.longitude)!
print(myLatitude)
print(myLongitude)
locationLatitude = myLatitude
locationLongitude = myLongitude
point1.coordinate = CLLocationCoordinate2DMake(myLatitude, myLongitude)
point2.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
mapView.addAnnotation(point2)
mapView.centerCoordinate = point2.coordinate
mapView.delegate = self
//Span of the map
// mapView.setRegion(MKCoordinateRegionMake(point2.coordinate, MKCoordinateSpanMake(0.7,0.7)), animated: true)
let directionsRequest = MKDirectionsRequest()
let markSource = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point1.coordinate.latitude, point1.coordinate.longitude), addressDictionary: nil)
let markDestination = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point2.coordinate.latitude, point2.coordinate.longitude), addressDictionary: nil)
directionsRequest.source = MKMapItem(placemark: markSource)
directionsRequest.destination = MKMapItem(placemark: markDestination)
directionsRequest.transportType = MKDirectionsTransportType.automobile
let directions = MKDirections(request: directionsRequest)
directions.calculate { (response, error) in
if error == nil {
self.myRoute = response!.routes[0] as MKRoute
for step in self.myRoute!.steps {
print(step.instructions)
}
var regionRect = self.myRoute?.polyline.boundingMapRect
let wPadding = regionRect!.size.width * 0.5
let hPadding = regionRect!.size.height * 0.5
//Add padding to the region
regionRect!.size.width += wPadding
regionRect!.size.height += hPadding
//Center the region on the line
regionRect!.origin.x -= wPadding / 2
regionRect!.origin.y -= hPadding / 2
self.mapView.setRegion(MKCoordinateRegionForMapRect(regionRect!), animated: true)
self.mapView.add((self.myRoute?.polyline)!)
} else {
print("Error calculating directions")
}
}
}
}