[英]How to geocode address by google maps iOS API?
我找到了一種發送請求的方法:
Google Maps Geocoding API請求采用以下格式:
https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters其中outputFormat可以是以下值之一:
json(推薦)表示JavaScript Object Notation(JSON)中的輸出; 或xml表示XML格式的輸出要通過HTTP訪問Google Maps Geocoding API,請使用:
但它真的很不方便,有什么本地方式在swift?
我查看了GMSGeocoder接口,只能通過它的API完成反向地理編碼。
正如其他人所指出的,沒有預定義的方法來進行搜索,但您可以使用網絡請求自行訪問Google地理編碼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()
}
不,Google Maps SDK for iOS中沒有原生方式。
這是一個非常受歡迎的功能請求,請參閱: 問題5170:功能請求:轉發地理編碼(從地址到坐標)
如果您只是在尋找Geocoding解決方案,您可以查看我構建的一個小型開源項目。 它非常輕量級,使用名為Nominatim的OpenStreetMap地理編碼API。 在這里查看: https : //github.com/caloon/NominatimSwift
你甚至可以搜索地標。
地理編碼地址和地標:
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)!)
})
不幸的是,沒有辦法像原生那樣做。 我希望這個功能會有所幫助。
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
}
}
}
Alamofire和Google的Geodecode API
斯威夫特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)
}
}
}
您可以使用地方搜索 Google Places API通過地址的網址會話發送請求,然后解析json結果。 它可能不完美但你可以得到除坐標以外的更多信息。
Google Maps API iOS SDK中沒有原生方式。 正如其他答案中所提到的,它已成為多年來所要求的功能 。
需要記住的一點是,Google Maps API主要專注於創建地圖:這是主要目標。
您必須使用基於URL的API調用或其他一些服務。 例如,一個名為SmartyStreets的不同服務有一個iOS SDK,它支持前向地理編碼。 以下是來自iOS SDK文檔頁面的 Swift示例代碼:
// 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
}
}
完全披露:我曾在SmartyStreets工作過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.