我正在尝试获取当前用户位置的CLLocationManager实例的经纬度坐标。
我在viewWillAppear方法中有这两行代码:
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
然后我有一个叫做startRoute
的方法来计算从当前位置到地图上某个特定注释的路线。然后画出这些路径之间的路线。不幸的是,这可以在地图上使用两个注释,但是我不能让它与用户的当前位置和一些注释一起工作。
我试过下面的脚本,但是当我打印print("LAT (currentLocation.coordinate.latitude)")
时,它会给我0.0
作为结果。
func startRoute() {
// Set the latitude and longtitude of the locations (markers)
let sourceLocation = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
let destinationLocation = CLLocationCoordinate2D(latitude: sightseeing.latitude!, longitude: sightseeing.longitude!)
// Create placemark objects containing the location's coordinates
let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
// MKMapitems are used for routing. This class encapsulates information about a specific point on the map
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
// Annotations are added which shows the name of the placemarks
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = "Times Square"
if let location = sourcePlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
let destinationAnnotation = MKPointAnnotation()
destinationAnnotation.title = "Title"
destinationAnnotation.subtitle = "Subtitle"
if let location = destinationPlacemark.location {
destinationAnnotation.coordinate = location.coordinate
}
// The annotations are displayed on the map
self.mapView.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )
// The MKDirectionsRequest class is used to compute the route
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .walking
// Calculate the direction
let directions = MKDirections(request: directionRequest)
// The route will be drawn using a polyline as a overlay view on top of the map.
// The region is set so both locations will be visible
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: (error)")
}
return
}
let route = response.routes[0]
self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}
在顶部,直接在类声明之后,我创建了对location manager
和'CLLocation'的引用:
var locationManager: CLLocationManager!
var currentLocation = CLLocation()
毕竟,这不起作用。只有当我将sourceLocation更改为硬编码坐标时,它才会绘制到目的地的路线。我做错了什么,或者我错过了什么?
但是当我输出
print("LAT (currentLocation.coordinate.latitude)")
时它会输出0.0
作为结果
当然有。它还能做什么?你有一个属性
var currentLocation = CLLocation()
这是一个零位置。你有没有代码曾经改变这个。因此总是为零位置。
你说你想要
当前用户位置
但是没有任何代码可以让获取用户的位置