swifthttprequestgoogle-elevation-api

Swift HTTP Request to Google Elevation API


Im trying to send requests to the Google Elevation API, I have successfully sent singular requests. Stated in the documentation for GE API is that a singular request can contain many coordinate evaluations if the coordinates are passed as a list separated by "|".

As you can see in my code I am following the format with requests containing something like this >> 3.222,54.333 | 2.444, 66.4332 | ...

This should be working from what I can tell but clearly something is wrong.

here is a segment of the code, the program breaks at the error point within this block.

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

Solution

  • try something like this, once you figure out what's in 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")
    

    EDIT: starting with an array of strings as described:

            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[$0], rawData[$0.advanced(by: 1)])}
            print("\n---> pairs: \(pairs)")
            
            let locs = pairs.map{ $0 + "," + $1 }.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")