Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to geocode address by google maps iOS API?

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.

like image 229
Jurasic Avatar asked Dec 05 '16 10:12

Jurasic


People also ask

Is Geocoding API free Google?

The Geocoding API uses a pay-as-you-go pricing model. Geocoding API requests generate calls to one of two SKUs depending on the type of request: basic or advanced.

Is there any free Geocoding API?

positionstack - Free Address Geocoding & Maps API.


2 Answers

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()
}
like image 131
Rob Avatar answered Sep 20 '22 16:09

Rob


Alamofire and Google's Geodecode API

Swift 4

func getAddressFromLatLong(latitude: Double, longitude : Double) {
    let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=YOUR_API_KEY_HERE"

    Alamofire.request(url).validate().responseJSON { response in
        switch response.result {
        case .success:

            let responseJson = response.result.value! as! NSDictionary

            if let results = responseJson.object(forKey: "results")! as? [NSDictionary] {
                if results.count > 0 {
                    if let addressComponents = results[0]["address_components"]! as? [NSDictionary] {
                        self.address = results[0]["formatted_address"] as? String
                        for component in addressComponents {
                            if let temp = component.object(forKey: "types") as? [String] {
                                if (temp[0] == "postal_code") {
                                    self.pincode = component["long_name"] as? String
                                }
                                if (temp[0] == "locality") {
                                    self.city = component["long_name"] as? String
                                }
                                if (temp[0] == "administrative_area_level_1") {
                                    self.state = component["long_name"] as? String
                                }
                                if (temp[0] == "country") {
                                    self.country = component["long_name"] as? String
                                }
                            }
                        }
                    }
                }
            }
        case .failure(let error):
            print(error)
        }
    }
}
like image 45
Sathish Kumar Avatar answered Sep 20 '22 16:09

Sathish Kumar