Google矩阵 - 计算出发地和目的地之间的距离

时间:2017-06-16 10:07:46

标签: swift google-maps swift3

我正在尝试构建Google矩阵服务请求,该服务将返回原点和目的地之间的距离。

以下:Google Docs

无法弄清楚如何构建正确的请求。

SUCCESS: {
    "destination_addresses" =     (
    );
    "origin_addresses" =     (
    );
    rows =     (
    );
    status = "INVALID_REQUEST";
}

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&destinations%5B%5D=30.37577%2C-81.7837&destinations%5B%5D=26.89648%2C-82.00874&destinations%5B%5D=30.48638%2C-84.42159&destinations%5B%5D=35.11241%2C-80.95421&destinations%5B%5D=33.82343%2C-84.12118&destinations%5B%5D=33.67012%2C-78.93803&destinations%5B%5D=39.87034%2C-82.94822&destinations%5B%5D=42.14669%2C-87.83312&destinations%5B%5D=42.65981%2C-84.55101&destinations%5B%5D=39.87016%2C-82.9482&destinations%5B%5D=39.86784%2C-82.94884&destinations%5B%5D=39.87014%2C-82.94824&destinations%5B%5D=39.87021%2C-82.94826&destinations%5B%5D=42.67464%2C-82.83249&destinations%5B%5D=39.87025%2C-82.94812&destinations%5B%5D=39.87049%2C-82.94807&destinations%5B%5D=39.87057%2C-82.94829&destinations%5B%5D=40.43237%2C-74.48872&destinations%5B%5D=39.96912%2C-82.99415&destinations%5B%5D=40.44534%2C-74.41769&destinations%5B%5D=40.4453%2C-74.41779&destinations%5B%5D=41.28482%2C-72.93002&destinations%5B%5D=40.44524%2C-74.41776&destinations%5B%5D=40.44559%2C-74.41811&destinations%5B%5D=42.12788%2C-75.97026&destinations%5B%5D=40.44576%2C-74.41788&destinations%5B%5D=40.69494%2C-74.09928&destinations%5B%5D=40.76857%2C-73.73745&destinations%5B%5D=40.4856%2C-74.39982&destinations%5B%5D=30.26164%2C-98.8715&destinations%5B%5D=39.95258%2C-82.90484&destinations%5B%5D=32.69126%2C-96.24597&destinations%5B%5D=29.48223%2C-98.34786&destinations%5B%5D=32.82934%2C-97.03087&destinations%5B%5D=32.8292%2C-97.03081&key=NOPE_THATS_MY_KEY&origins=37.6724723880042%2C-90.4441829064476

我构建目标数组的方式:

func createDestinationsArray(annotations: [MyAnnotation]) -> [String] {
        var destinations: [String] = []
        var destination: String!

        for annotation in annotations {
            destination = "\(annotations.lat),\(annotations.lon)"
            destinations.append(destination)
        }

        return destinations
    }

请求:

let queue = DispatchQueue(label: "com.cnoon.distance-queue", qos: .utility, attributes: .concurrent)


 Alamofire.request(url, method: .get, parameters: ["origins" : origins, "destinations" : destinations, "key" : apiKey]).response(queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(), completionHandler: { response in 
 ...
})

提前致谢!!

1 个答案:

答案 0 :(得分:0)

文档清楚地表明,您应该将|作为数组元素之间的分隔符。此外,您在每个坐标对前附加目的地,如果您查看文档,这显然是错误的。你有两个选择。在第一个位置创建目标和源数组作为字符串,包含分隔符或稍后将数组连接到带分隔符的字符串。因为据我所知,除了网络请求之外你不需要你的数组,我认为直接生成一个字符串是更优化的解决方案。

func createDestinationsArray(annotations: [MyAnnotation]) -> String {
    return annotations.map({ return "\($0.latitude),\($0.longitude)" }).joined(separator: "|")
}