How to geocode an address using google iOS API maps?

I found one way to send a request:

The request for the Google Maps geocoding API is as follows:

https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters where outputFormat can have one of the following values:

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

But this is really inconvenient, is there any home way in the fast?

I looked at the GMSGeocoder interface and only reverse geocoding can be done using the API.

+8
source share
7 answers

As others have already pointed out, there is no predefined method for searching, but you can use the 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, eg grab 'formatted_address': let strings = results.compactMap { $0["formatted_address"] as? String } ... } } task.resume() } 
+15
source

No, there is no native path in the Google Maps SDK for iOS.

This is a very popular function request, see: Problem 5170: Function request: Geocoding transfer (from address to coordinates)

+5
source

If you're just looking for a geocoding solution, you can explore the small open source project that I built. It is very lightweight and uses the OpenStreetMap geocoding API called Nominatim. Take a look here: https://github.com/caloon/NominatimSwift

You can even find landmarks.

Geocoding addresses and landmarks:

 Nominatim.getLocation(fromAddress: "The Royal Palace of Stockholm", completion: {(error, location) -> Void in print("Geolocation of the Royal Palace of Stockholm:") print("lat = " + (location?.latitude)! + " lon = " + (location?.longitude)!) }) 
+3
source

Unfortunately, there is no way to do this as native. I hope this feature helps.

  func getAddress(address:String){ let key : String = "YOUR_GOOGLE_API_KEY" let postParameters:[String: Any] = [ "address": address,"key":key] let url : String = "https://maps.googleapis.com/maps/api/geocode/json" Alamofire.request(url, method: .get, parameters: postParameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in if let receivedResults = response.result.value { let resultParams = JSON(receivedResults) print(resultParams) // RESULT JSON print(resultParams["status"]) // OK, ERROR print(resultParams["results"][0]["geometry"]["location"]["lat"].doubleValue) // approximately latitude print(resultParams["results"][0]["geometry"]["location"]["lng"].doubleValue) // approximately longitude } } } 
+2
source

You can send a request via the URL address using the Post Search Google Places API, and then parse the json result. This may not be perfect, but you can get more information than coordinates.

+1
source

The Google Maps API SDK API does not have its own path. As mentioned in other answers, this has been a requested feature for many years .

Keep in mind that the Google Maps API is mainly focused on creating maps: this is the main goal.

You should use APIs or some other services. For example, another service called SmartyStreets has an iOS SDK that has built-in support for advanced geocoding. Here's a sample code for Swift from their iOS SDK documentation page :

 // Swift: Sending a Single Lookup to the US ZIP Code API package examples; import Foundation import SmartystreetsSDK class ZipCodeSingleLookupExample { func run() -> String { let mobile = SSSharedCredentials(id: "SMARTY WEBSITE KEY HERE", hostname: "HOST HERE") let client = SSZipCodeClientBuilder(signer: mobile).build() // Uncomment the following line to use Static Credentials // let client = SSZipCodeClientBuilder(authId: "YOUR AUTH-ID HERE", authToken: "YOUR AUTH-TOKEN HERE").build() let lookup = SSZipCodeLookup() lookup.city = "Mountain View" lookup.state = "California" do { try client?.send(lookup) } catch let error as NSError { print(String(format: "Domain: %@", error.domain)) print(String(format: "Error Code: %i", error.code)) print(String(format: "Description: %@", error.localizedDescription)) return "Error sending request" } let result: SSResult = lookup.result let zipCodes = result.zipCodes let cities = result.cities var output: String = String() if (cities == nil && zipCodes == nil) { output += "Error getting cities and zip codes." return output } for city in cities! { output += "\nCity: " + (city as! SSCity).city output += "\nState: " + (city as! SSCity).state output += "\nMailable City: " + ((city as! SSCity).mailableCity ? "YES" : "NO") + "\n" } for zip in zipCodes! { output += "\nZIP Code: " + (zip as! SSZipCode).zipCode output += "\nLatitude: " + String(format:"%f", (zip as! SSZipCode).latitude) output += "\nLongitude: " + String(format:"%f", (zip as! SSZipCode).longitude) + "\n" } return output } } 

Full disclosure: I worked at SmartyStreets.

0
source

Alamofire and Google 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) } } } 
0
source

Source: https://habr.com/ru/post/1012893/


All Articles