我正在尝试使用 Google map 获取从用户当前位置到目的地的路线。我希望在按下 showDirection 按钮时完成此操作,但是我不知道如何从 func locationManager(... didUpdateLocation) 返回或将用户位置传递给 IBAction 函数,因为 IBAction 不使用其中的参数我可以将 locValue 传递给。
这里是 showDirection 按钮函数:
@IBAction func showDirection(sender: AnyObject) {
print("Running showDirection")
let instanceOne = ParseViewController() // Create ParseViewController instance to operate on
print("Created ParseView instance")
let Coord = instanceOne.returnParse()
let latitude = (Coord.lat as NSString)
let longitude = (Coord.long as NSString)
var urlString = "http://maps.google.com/maps?"
urlString += "saddr= // Users location from didUpdateLocation"
urlString += "&daddr= \(latitude as String), \(longitude as String)"
print(urlString)
if let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
{
UIApplication.sharedApplication().openURL(url)
}
}
这里是带有 locValue 的 locationManager 函数:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!
print("Coordinates = \(locValue.latitude), \(locValue.longitude)")
locationManager.stopUpdatingLocation()
}
}
非常感谢任何帮助!
最佳答案
如果你想在另一个函数中使用它,你需要在类中创建一个内部变量来存储位置。例如
class YourViewController: UIViewController ... {
var lastLocation: CLLocation? = nil
...
}
在 didUpdateLocations
中:
if let location = locations.first {
lastLocation = location
...
}
现在您可以在 func showDirection()
中访问它
关于ios - Swift - 从类扩展中的 locationManager 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261201/