Google maps Google Driections API从Swift 3中的闭包返回一个数组
我是Swift新手,我正在尝试使用谷歌方向API。我修改了一个函数来获得一条多段线,并将Google方向放入一个数组中。我声明为我正在使用的类的属性的方向数组,以便在表中显示结果。我已经检查过了,数组中正确填充了闭包内的方向。但是,当我尝试在CellForTableAT函数的闭包之外使用它时,它是空的。我可能没有正确地从闭包中获取数据,但我无法理解。我从//MARK开始构建阵列:开始使用swiftyJason构建方向阵列Google maps Google Driections API从Swift 3中的闭包返回一个数组,google-maps,swift3,closures,google-directory-api,Google Maps,Swift3,Closures,Google Directory Api,我是Swift新手,我正在尝试使用谷歌方向API。我修改了一个函数来获得一条多段线,并将Google方向放入一个数组中。我声明为我正在使用的类的属性的方向数组,以便在表中显示结果。我已经检查过了,数组中正确填充了闭包内的方向。但是,当我尝试在CellForTableAT函数的闭包之外使用它时,它是空的。我可能没有正确地从闭包中获取数据,但我无法理解。我从//MARK开始构建阵列:开始使用swiftyJason构建方向阵列 func getDirections(currentDestination
func getDirections(currentDestination: GMSMarker, origin: String!, destination: String!, waypoints: Array<String>!, mode: String!, completionHandler: ((_ status: String, _ success: Bool) -> Void)?) {
if let originLocation = origin {
if let destinationLocation = destination {
var directionsURLString = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation + "&mode=" + mode
if let routeWaypoints = waypoints {
directionsURLString += "&waypoints=optimize:true"
for waypoint in routeWaypoints {
directionsURLString += "|" + waypoint
}
}
directionsURLString = ("\(directionsURLString)&sensor=true&key=???????????????")
print("directons*******")
print(directionsURLString)
directionsURLString = directionsURLString.addingPercentEscapes(using: String.Encoding.utf8)!
let directionsURL = NSURL(string: directionsURLString)
DispatchQueue.main.async( execute: { () -> Void in
let directionsData = NSData(contentsOf: directionsURL! as URL)
do{
let dictionary: Dictionary<String, AnyObject> = try JSONSerialization.jsonObject(with: directionsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, AnyObject>
let status = dictionary["status"] as! String
let json = JSON(data: directionsData as! Data)
if status == "OK" {
self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<String, AnyObject>>)[0]
self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<String, AnyObject>
let legs = self.selectedRoute["legs"] as! Array<Dictionary<String, AnyObject>>
let startLocationDictionary = legs[0]["start_location"] as! Dictionary<String, AnyObject>
self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double)
let endLocationDictionary = legs[legs.count - 1]["end_location"] as! Dictionary<String, AnyObject>
self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double)
let originAddress = legs[0]["start_address"] as! String
let destinationAddress = legs[legs.count - 1]["end_address"] as! String
for (index, leg) in json["routes"][0]["legs"].arrayValue.enumerated() {
var count = 0
//MARK: Start Building Directions Array
for (stepIndex, step) in json["routes"][0]["legs"][index]["steps"].arrayValue.enumerated() {
count += 1
let htmlInstructions = json["routes"][0]["legs"][index]["steps"][stepIndex]["html_instructions"].string
let distance = json["routes"][0]["legs"][index]["steps"][stepIndex]["distance"]["text"].string
let duration = json["routes"][0]["legs"][index]["steps"][stepIndex]["duration"]["text"].string
let direction:Direction = Direction(index: count, htmlInstructions: htmlInstructions, distance: distance, duration: duration)
self.directions.append(direction)
}
self.tableView.reloadData()
}
//end of stepts to get writtine directions
//NOT Plotting markers endpoins
//position markers for ployline endpoints
//let originMarker = GMSMarker(position: self.originCoordinate)
// originMarker.map = self.mapView
//originMarker.icon = UIImage(named: "mapIcon")
// originMarker.title = originAddress
self.destinationMarker = currentDestination
// destinationMarker.map = self.mapView
// destinationMarker.icon = UIImage(named: "mapIcon")
// destinationMarker.title = destinationAddress
// destinationMarker.icon = GMSMarker.markerImage(with: UIColor.green)
if waypoints != nil && waypoints.count > 0 {
for waypoint in waypoints {
let lat: Double = (waypoint.components(separatedBy: ",")[0] as NSString).doubleValue
let lng: Double = (waypoint.components(separatedBy: ",")[1] as NSString).doubleValue
let marker = GMSMarker(position: CLLocationCoordinate2DMake(lat, lng))
marker.map = self.mapView
marker.icon = UIImage(named: "mapIcon")
}
}
self.routePolyline.map = nil
let route = self.overviewPolyline["points"] as! String
let path: GMSPath = GMSPath(fromEncodedPath: route)!
self.routePolyline = GMSPolyline(path: path)
self.routePolyline.map = self.mapView
self.routePolyline.strokeColor = UIColor.red
self.routePolyline.strokeWidth = 3.0
//Fit map to entire polyline
var bounds = GMSCoordinateBounds()
for index in 1...path.count() {
bounds = bounds.includingCoordinate(path.coordinate(at: index))
}
self.mapView.animate(with: GMSCameraUpdate.fit(bounds))
// end of fit map to ployline
}
else {
print("status of poly draw")
//completionHandler(status: status, success: false)
}
}
catch {
print("catch")
// completionHandler(status: "", success: false)
}
})
}
else {
print("Destination is nil.")
//completionHandler(status: "Destination is nil.", success: false)
}
}
else {
print("Origin is nil")
//completionHandler(status: "Origin is nil", success: false)
}
}
func-getDirections(当前目的地:GMSMarker,原点:String!,目的地:String!,航路点:Array!,模式:String!,completionHandler:(((uu-status:String,uu-success:Bool)->Void)?){
如果让originLocation=原点{
如果让destinationLocation=目的地{
var directionsURLString=baseURLDirections+“origin=“+originLocation+”&destination=“+destinationLocation+”&mode=“+mode
如果让航路点=航路点{
directionsURLString+=“&waypoints=optimize:true”
对于航路点中的航路点{
方向URLSTRING+=“|”+航路点
}
}
directionsURLString=(“\(directionsURLString)&sensor=true&key=??”)
打印(“指令*******”)
打印(方向URL字符串)
directionsURLString=directionsURLString.addingPercentEscapes(使用:String.Encoding.utf8)!
让directionsURL=NSURL(字符串:directionsURLString)
DispatchQueue.main.async(在中执行:{()->Void
让directionsData=NSData(内容:directionsURL!作为URL)
做{
让dictionary:dictionary=try JSONSerialization.jsonObject(使用:directionsData!作为数据,选项:JSONSerialization.ReadingOptions.mutableContainers)作为!dictionary
让status=dictionary[“status”]作为!字符串
让json=json(数据:directionsdataas!data)
如果状态==“正常”{
self.selectedRoute=(字典[“路由”]作为!数组)[0]
self.overview polyline=self.selectedRoute[“overview\u polyline”]作为字典
让legs=self.selectedRoute[“legs”]作为!数组
让startLocationDictionary=legs[0][“开始位置”]作为!Dictionary
self.originCoordinate=CLLocationCoordinate2DMake(startLocationDictionary[“lat”]as!Double,startLocationDictionary[“lng”]as!Double)
让endLocationDictionary=legs[legs.count-1][“end\u location”]作为!Dictionary
self.destinationCoordinate=CLLocationCoordinate2DMake(endLocationDictionary[“lat”]as!Double,endLocationDictionary[“lng”]as!Double)
将originAddress=legs[0][“起始地址”]设为!字符串
让destinationAddress=legs[legs.count-1][“end_address”]作为!字符串
对于json[“路由”][0][“分支”].arrayValue.enumerated()中的(索引,分支){
变量计数=0
//标记:开始构建方向阵列
对于json[“路由”][0][“腿”][index][“步骤”].arrayValue.enumerated()中的(步骤索引,步骤){
计数+=1
让htmlInstructions=json[“路由”][0][“腿”][index][“步骤”][stepIndex][“html_指令”]。字符串
让距离=json[“路由”][0][“腿”][index][“步数”][stepIndex][“距离”][“文本”]。字符串
let duration=json[“路由”][0][“腿”][index][“步骤”][stepIndex][“持续时间”][“文本”]。字符串
让方向:方向=方向(索引:计数,htmlInstructions:htmlInstructions,距离:距离,持续时间:持续时间)
self.directions.append(方向)
}
self.tableView.reloadData()
}
//获取写入方向的步骤结束
//不绘制端点标记
//多边形端点的位置标记
//让originMarker=GMSMarker(位置:self.originCoordinate)
//originMarker.map=self.mapView
//originMarker.icon=UIImage(名为:“mapIcon”)
//originMarker.title=originAddress
self.destinationMarker=currentDestination
//destinationMarker.map=self.mapView
//destinationMarker.icon=UIImage(名为:“mapIcon”)
//destinationMarker.title=destinationAddress
//destinationMarker.icon=GMSMarker.markerImage(带:UIColor.green)
如果航路点!=nil&&waypoints.count>0{
对于航路点中的航路点{
设lat:Double=(航路点.components(以“,”[0]分隔,作为NSString)。doubleValue
设lng:Double=(航路点.components(以“,”[1]分隔,作为NSString)。doubleValue
让标记器=GMS标记器(位置:CLLocationCoordinate2DMake(lat,lng))
marker.map=self.mapView
marker.icon=UIImage(名为:“mapIcon”)
}
}
self.routePolyline.map=nil
让route=self.Overview多段线[“点”]作为!字符串
让路径:GMSPath=GMSPath(fromEncodedPath:route)!
func getDirections(currentDestination: GMSMarker, origin: String!, destination: String!, waypoints: Array<String>!, mode: String!, completionHandler: ((_ status: String, _ success: Bool) -> Void)?) -> ([Direction])