2016-12-05 141 views
5

我发现发送请求的一种方法:如何通过谷歌地图iOS API对地址进行地理编码?

甲谷歌地图地址解析API请求采用以下形式:

https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters 其中OUTPUTFORMAT可以是以下值之一:

JSON(推荐)以JavaScript Object Notation (JSON)表示输出;或xml表示输出XML要通过HTTP访问所使用的谷歌地图 地理编码API:

但它确实不方便,有没有任何迅速原生的方式?

我看着GMSGeocoder接口,只有反向地理编码可以通过它的API完成。

回答

4

如果你只是寻找一个解决方案地理编码你可以寻找到一个小的开源项目我建。它非常轻便,并使用OpenStreetMap的地理编码API(称为Nominatim)。看看这里: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)!) 
}) 
0

有一个在谷歌地图API的iOS SDK没有原生的方式。正如其他答案中提到的那样,这是一个requested feature for years

有一点要记住的是,Google Maps API主要关注于创建地图:这是主要目标。

您必须使用基于URL的API调用或其他服务。例如,名为SmartyStreets的另一个服务具有iOS SDK,该SDK具有对前向地理编码的本机支持。下面是斯威夫特的例子代码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 
    } 
} 

全面披露:我为SmartyStreets工作。

9

正如其他人所指出的那样,没有一个预定义的方法做搜索,但您可以使用网络请求访问Google Geocoding 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.flatMap { $0["formatted_address"] as? String } 
      ... 
     } 
    } 

    task.resume() 
} 
1

您可以通过对URL会话发送请求地址使用Google Places API的Place Search,然后解析json结果。它可能并不完美,但您可以获得除坐标以外的更多信息。

1

不幸的是,没有办法做到原生。我希望这个功能会有所帮助。

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 
     } 
    } 
}