我正在使用谷歌自动完成(GMSAutocompletePrediction)来获取attributedFullText(result.attributedFullText.string),所选择的建议在以下代码中使用,这是从attributedFullText获取纬度和经度的地理编码。对于许多不同的地方,返回的原点是我正在查看的城市的市中心。
知道使用的语言是阿拉伯语
if let correctedAddress = self.allAddresses[0][(indexPath as NSIndexPath).row].full.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false") {
print(correctedAddress)
print(self.allAddresses[0][(indexPath as NSIndexPath).row].full)
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
// 3
do {
if data != nil{
if let jsonObject = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any],
let results = jsonObject["results"] as? [[String:Any]], !results.isEmpty,
let geometry = results[0]["geometry"] as? [String:Any],
let location = geometry["location"] as? [String:Double],
let lat = location["lat"], let lng = location["lng"] {
print("\(lat) - \(lng)")
let newAddress = Address(name: self.allAddresses[0][(indexPath as NSIndexPath).row].name , detail: self.allAddresses[0][(indexPath as NSIndexPath).row].detail, latitude: String(lat), longitude: String(lng))
// go back to the previous view controller
self.delegate?.userDidChooseLocation(newAddress)
self.dismiss(animated: true, completion: nil)
}
}
}catch {
print("Error")
}
})
// 5
task.resume()
}
}
}
最佳答案
使用地点 ID 会更好:
您还可以使用自动完成中的地点 ID 查询 Google Maps Geocoding API Web 服务:
https://maps.googleapis.com/maps/api/geocode/json?place_id=(placeId)&key=YOUR_API_KEY
请注意,此类请求需要 API key 。
此外,传感器参数早已退役。
关于ios - 谷歌地理编码不断返回不同地方的市中心位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164199/