Swift 对 Google 海拔 API 的 HTTP 请求

Swift HTTP Request to Google Elevation API

我正在尝试向 Google 海拔 API 发送请求,我已成功发送单个请求。 GE API 的文档中指出,如果坐标作为由“|”分隔的列表传递,则单个请求可以包含许多坐标评估。

正如您在我的代码中看到的那样,我遵循的请求格式包含如下内容 >> 3.222,54.333 | 2.444, 66.4332 | ...

据我所知,这应该是有效的,但显然有问题。

这是一段代码,程序在该块内的错误点处中断。

finalStringConvertedCoordinates = processedQueryPoints.joined(separator: "|")
        let apiKey = "REDACTED"
        guard let url = URL(string: "https://maps.googleapis.com/maps/api/elevation/json?key=\(apiKey)&locations=\(finalStringConvertedCoordinates)") else {
                    print("Error: cannot create URL")
                    return

尝试这样的事情,一旦你弄清楚 processedQueryPoints 中的内容:

        let locations = ["3.222,54.333", "2.444,66.4332"]
        let locs = locations.joined(separator: "%7C")  // <-- the important bit
        print("\n---> locs: \(locs)")
        let apiKey = "REDACTED"
        let url = URL(string: "https://maps.googleapis.com/maps/api/elevation/json?locations=\(locs)&key=\(apiKey)")
        print("---> url: \(url) \n")

编辑:从描述的字符串数组开始:

        let rawData = ["3.222","54.333", "2.444","66.4332"]
        print("\n---> rawData: \(rawData)")
        
        let pairs = stride(from: 0, to: rawData.endIndex, by: 2).map {(rawData[[=11=]], rawData[[=11=].advanced(by: 1)])}
        print("\n---> pairs: \(pairs)")
        
        let locs = pairs.map{ [=11=] + "," +  }.joined(separator: "%7C")
        print("\n---> locs: \(locs)")
        
        let apiKey = "REDACTED"
        let url = URL(string: "https://maps.googleapis.com/maps/api/elevation/json?locations=\(locs)&key=\(apiKey)")
        print("---> url: \(url) \n")