使用Google Maps API在Swift 3中查找2个位置之间的驾驶/步行距离

hiz5n14c  于 2023-02-07  发布在  Swift
关注(0)|答案(2)|浏览(209)

我正在尝试使用Google Maps API获取两个地点之间的驾驶/步行距离。我正在将我的应用程序从objective-c更新为Swift 3,现在我正将这段代码转换为Swift 3。

NSString *dist;
NSString *strUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false&mode=%@", closestLocation.coordinate.latitude,  closestLocation.coordinate.longitude, _currentUserLocation.coordinate.latitude,  _currentUserLocation.coordinate.longitude, @"DRIVING"];
NSURL *url = [NSURL URLWithString:[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if(jsonData != nil)
{
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSMutableArray *arrDistance=[result objectForKey:@"routes"];
    if ([arrDistance count]==0) {
        NSLog(@"N.A.");
    }
    else{
        NSMutableArray *arrLeg=[[arrDistance objectAtIndex:0]objectForKey:@"legs"];
        NSMutableDictionary *dictleg=[arrLeg objectAtIndex:0];

        dist = [NSString stringWithFormat:@"%@",[[dictleg   objectForKey:@"distance"] objectForKey:@"text"]];
    }
}
else{
    NSLog(@"N.A.");
}

我试过使用Swiftify这样的工具,但到处都是错误。我现在拥有的是:

var dist: String = ""
var strUrl: String = "http://maps.googleapis.com/maps/api/directions/json?origin=\(closestLocation!.coordinate.latitude),\(closestLocation!.coordinate.longitude)&destination=\(currentUserLocation!.coordinate.latitude),\(currentUserLocation!.coordinate.longitude)&sensor=false&mode=\("DRIVING")"
var url = URL(string: strUrl)
var jsonData = Data(contentsOf: url!)
    if (jsonData != nil) {
        var error: Error? = nil
        var result: Any? = try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.Element.mutableContainers)
        var arrDistance: [Any]? = (result?["routes"] as? [Any])
        if arrDistance?.count == 0 {
            print("N.A.")
        }
        else {
            var arrLeg: [Any]? = ((arrDistance?[0] as? [Any])?["legs"] as? [Any])
            var dictleg: [AnyHashable: Any]? = (arrLeg?[0] as? [AnyHashable: Any])

            dist = "\(dictleg?["distance"]["text"])"
        }
    }
    else {
        print("N.A.")
    }

我现在的错误如下:
与数据(内容属于:url!)它告诉我“调用可以抛出,但它没有标记'try',错误没有得到处理
它不喜欢我用[Any]作为arrDistance变量。
如果有人知道如何在Swift 3中实现这个API调用,那将非常有帮助。

lp0sw83n

lp0sw83n1#

什么编译器是说Data(contentsOf:)throws异常,所以你需要处理它与do catch块。现在建议在评论中,你需要使用dataTask(with:)而不是Data(contentsOf:)下载数据。你也可以使完成块与你的代码,所以在你的代码做如下所示的变化。

func getDistance(completion: @escaping(String) -> Void) {

    var dist = ""
    let strUrl = "http://maps.googleapis.com/maps/api/directions/json?origin=\(closestLocation!.coordinate.latitude),\(closestLocation!.coordinate.longitude)&destination=\(currentUserLocation!.coordinate.latitude),\(currentUserLocation!.coordinate.longitude)&sensor=false&mode=\("DRIVING")"
    let url = URL(string: strUrl)!
    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "")
            completion(dist)
            return
        }
        if let result = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:Any],
            let routes = result["routes"] as? [[String:Any]], let route = routes.first,
            let legs = route["legs"] as? [[String:Any]], let leg = legs.first,
            let distance = leg["distance"] as? [String:Any], let distanceText = distance["text"] as? String {

            dist = distanceText
        }
        completion(dist)
    })
    task.resume()
}

现在只需像这样调用getDistance函数。

self.getDistance { (distance) in
    //Update UI on main thread
    DispatchQueue.main.async {
        print(distance)
        self.label.text = distance
    }
}
abithluo

abithluo2#

    • 斯威夫特5+:**

如果有人用CoreLocation寻找答案。
据我所知,有两种方法来计算距离。如果你要计算驾驶距离,你可以使用MKDirections。下面是计算驾驶距离的代码(你也可以通过改变交通工具类型来计算步行和中转距离)。

let sourceP = CLLocationCoordinate2DMake( sourceLat, sourceLong)
let destP = CLLocationCoordinate2DMake( desLat, desLong)
let source = MKPlacemark(coordinate: sourceP)
let destination = MKPlacemark(coordinate: destP)
        
let request = MKDirections.Request()
request.source = MKMapItem(placemark: source)
request.destination = MKMapItem(placemark: destination)

// Specify the transportation type
request.transportType = MKDirectionsTransportType.automobile;

// If you want only the shortest route, set this to a false
request.requestsAlternateRoutes = true

let directions = MKDirections(request: request)

 // Now we have the routes, we can calculate the distance using
 directions.calculate { (response, error) in
    if let response = response, let route = response.routes.first {
                print(route.distance) //This will return distance in meters
    }
 }

如果您只查找空中距离/鸟瞰距离/坐标距离,则可以使用此代码:

let sourceP = CLLocation(latitude: sourceLat, longitude: sourceLong)
let desP = CLLocation(latitude: desLat, longitude: desLong))

let distanceInMeter = sourceP.distance(from: desP)

相关问题