2016-12-05 7 views
5

私がリクエストを送信するための一つの方法が見つかりました:GoogleマップのジオコーディングAPIリクエストは次の形式を取りGoogleマップのiOS APIでアドレスをジオコードする方法は?

を:

OUTPUTFORMATは、次の値のいずれであってもよい

https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters

JSON(推奨)は、JavaScript Object Notation (JSON)の出力を示します。またはXMLは、HTTP経由でGoogleマップ ジオコーディングAPIにアクセスするにはXMLで出力、使用を示している:

をしかし、それは本当に不便だ、迅速で任意のネイティブな方法はありますか?

私はGMSGeocoderインターフェイスを調べて、そのAPIで逆ジオコーディングしか行うことができません。

答えて

4

をあなただけのジオコーディングソリューションを探しているなら、あなたは私が構築され、ほとんどのオープンソースプロジェクトに見ることができます。これは非常に軽量で、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)!) 
}) 
0

Google MapsのAPIのiOS SDKにはネイティブな方法はありません。他の回答でも触れたように、それはrequested feature for yearsでした。

覚えておいていただきたいのは、Google Maps APIは主に地図作成に重点を置いていることです。これが主な目的です。

URLベースのAPI呼び出しまたはその他のサービスを使用する必要があります。たとえば、SmartyStreetsという別のサービスには、iOS SDKがあります。これには、順方向ジオコーディングがネイティブサポートされています。

// 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のために働いている。ここtheir iOS SDK documentation pageからスウィフトのコード例です。他の人がそこに検索を行うには事前に定義された方法はありませんが、アクセスするために、ネットワーク要求を使用することができ、指摘したように

9

Google Geocoding API自身:あなたはのURLセッションを介して要求を送信することができます

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

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 
     } 
    } 
} 
関連する問題