ios - 如何通过 google maps iOS API 对地址进行地理编码?

标签 ios swift google-maps geocoding google-geocoding-api

我找到了一种发送请求的方法:

A Google Maps Geocoding API request takes the following form:

https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters where outputFormat may be either of the following values:

json (recommended) indicates output in JavaScript Object Notation (JSON); or xml indicates output in XML To access the Google Maps Geocoding API over HTTP, use:

但是确实很不方便,请问swift有没有native的方式?

我查看了 GMSGeocoder 接口(interface),发现它的 API 只能进行反向地理编码。

最佳答案

正如其他人所指出的,没有预定义的搜索方法,但您可以使用网络请求访问 Google Geocoding API你自己:

func performGoogleSearch(for string: String) {
    strings = nil
    tableView.reloadData()

    var components = URLComponents(string: "https://maps.googleapis.com/maps/api/geocode/json")!
    let key = URLQueryItem(name: "key", value: "...") // use your key
    let address = URLQueryItem(name: "address", value: string)
    components.queryItems = [key, address]

    let task = URLSession.shared.dataTask(with: components.url!) { data, response, error in
        guard let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, error == nil else {
            print(String(describing: response))
            print(String(describing: error))
            return
        }

        guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {
            print("not JSON format expected")
            print(String(data: data, encoding: .utf8) ?? "Not string?!?")
            return
        }

        guard let results = json["results"] as? [[String: Any]],
            let status = json["status"] as? String,
            status == "OK" else {
                print("no results")
                print(String(describing: json))
                return
        }

        DispatchQueue.main.async {
            // now do something with the results, e.g. grab `formatted_address`:
            let strings = results.compactMap { $0["formatted_address"] as? String }
            ...
        }
    }

    task.resume()
}

关于ios - 如何通过 google maps iOS API 对地址进行地理编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40971633/

相关文章:

ios - 无法将 iSpeech 导入我的 iOS Swift 项目

javascript - 如何在网页上的谷歌地图上添加地址?

ios - 连接到自定义类时单元格消失

ios - 使用全局变量在 ViewController 之间传递数据有哪些缺点?

ios - 有没有办法在设备之间共享应用程序配置?

ios - SwiftUI:从 ScrollView 中的底部对齐构建 View

google-maps - 在谷歌地图信息窗口angular2中显示自定义标签

asp.net - Google map 不会在 ASP.NET 母版页中显示

php - 并登录 POST var

ios - IOS (iPad 2) 上 AIR 3.9 中的 StageWebView