2016-12-05 46 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 
     } 
    } 
} 
相關問題