Jur*_*sic 9 google-maps geocoding ios google-geocoding-api swift
我找到了一种发送请求的方法:
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完成反向地理编码.
Rob*_*Rob 16
正如其他人所指出的,没有预定义的方法来进行搜索,但您可以使用网络请求自行访问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()
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,没有办法以原生方式做到这一点。我希望该功能能有所帮助。
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16225 次 |
| 最近记录: |