我是IOS编码和使用swift的新手 我试图计算两个不同点之间的ETA。当我将地址转换为坐标时,我将它们存储在全局变量中。问题是,由于该值是在完成处理程序中设置的,当我进行调用以计算ETA时,尚未设置变量。什么是获得相同结果的另一种方式。
sourceCoords: CLLocationCoordinate2D?
destCoords: CLLocationCoordinate2D?
func getETA()
{
var locationManager:CLLocationManager = CLLocationManager();
locationManager.requestAlwaysAuthorization();
var authorizationStatus:CLAuthorizationStatus = CLLocationManager.authorizationStatus();
if(authorizationStatus == CLAuthorizationStatus.Authorized ||
authorizationStatus == CLAuthorizationStatus.AuthorizedWhenInUse)
{
let geoCoder = CLGeocoder()
let sourceAddress =
[kABPersonAddressStreetKey as NSString: "1 Stockton St",
kABPersonAddressCityKey: "San Francisco",
kABPersonAddressStateKey: "California",
kABPersonAddressZIPKey: "94108"]
//get coordinates
geoCoder.geocodeAddressDictionary(sourceAddress, completionHandler:
{
(placemarks: [AnyObject]!, error: NSError!) in
if error != nil {
println("Geocode failed with error: \(error.localizedDescription)")
} else if placemarks.count > 0 {
let placemark = placemarks[0] as CLPlacemark
let location = placemark.location
self.sourceCoords = location.coordinate
}
});
//var requestSource = MKMapItem.mapItemForCurrentLocation();
let addressDict =
[kABPersonAddressStreetKey as NSString: "2125 Chestnut St",
kABPersonAddressCityKey: "San Francisco",
kABPersonAddressStateKey: "California",
kABPersonAddressZIPKey: "94123"]
//get coordinates
geoCoder.geocodeAddressDictionary(addressDict, completionHandler:
{
(placemarks: [AnyObject]!, error: NSError!) in
if error != nil {
println("Geocode failed with error: \(error.localizedDescription)")
} else if placemarks.count > 0 {
let placemark = placemarks[0] as CLPlacemark
let location = placemark.location
self.destCoords = location.coordinate
}
});
let placeSource = MKPlacemark(coordinate: sourceCoords!,
addressDictionary: sourceAddress)
var requestSource = MKMapItem(placemark: placeSource);
println(placeSource.location.coordinate.latitude)
let place = MKPlacemark(coordinate: destCoords!,
addressDictionary: addressDict)
var requestDestination = MKMapItem(placemark: place);
println(place.location.coordinate.latitude)
var request:MKDirectionsRequest = MKDirectionsRequest();
request.setSource(requestSource);
request.setDestination(requestDestination);
request.transportType = MKDirectionsTransportType.Automobile;
request.requestsAlternateRoutes = false;
var directions:MKDirections = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler({
(response: MKDirectionsResponse!, error: NSError?) in
if error != nil{
println("Error")
}
if response != nil{
var mkRoute:MKRoute = response.routes.last as MKRoute;
println(mkRoute.expectedTravelTime)
println(mkRoute.distance)
for step in mkRoute.steps
{
println(step.instructions);
}
}
else{
println("No response")
}
println(error?.description)
})
}