如何通过Google Maps iOS API对地址进行地址解析? [英] How to geocode address by google maps iOS API?

查看:49
本文介绍了如何通过Google Maps iOS API对地址进行地址解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found one way to send request:

Google Maps Geocoding API请求采用以下形式:

A Google Maps Geocoding API request takes the following form:

https://maps.googleapis.com/maps/api/geocode/outputFormat?参数 其中outputFormat可以是以下值之一:

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

json(推荐)指示以JavaScript对象表示法输出 (JSON);或xml表示XML的输出要访问Google Maps 通过HTTP的地址解析API,请使用:

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:

但这真的很不方便,是否有任何本机快速解决方法?

But it's really inconvenient, is there any native way in swift?

我查看了GMSGeocoder接口,并且只能通过其API进行反向地理编码.

I looked into GMSGeocoder interface and only reverse geocoding can be done by it's API.

推荐答案

正如其他人指出的那样,没有预定义的方法可以进行搜索,但是您可以使用网络请求来访问

As others have pointed out, there is not a predefined method to do the search, but you can use network request to access the Google Geocoding API yourself:

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()
}

这篇关于如何通过Google Maps iOS API对地址进行地址解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆