How to geocode address by google maps iOS API?

Jurasic picture Jurasic · Dec 5, 2016 · Viewed 22.1k times · Source

I found one way to send request:

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:

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

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

Answer

Rob picture Rob · Jul 3, 2017

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