如何通过谷歌地图iOS API对地址进行地理编码?

时间:2016-12-05 10:03:57

标签: ios swift google-maps geocoding google-geocoding-api

我找到了一种发送请求的方法:

  

Google Maps Geocoding API请求采用以下格式:

     

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

     

json(推荐)表示JavaScript Object Notation中的输出   (JSON);或xml表示XML格式的输出要访问Google地图   通过HTTP对地理编码API,使用:

但这真的很不方便,swift中有没有本地方式?

我查看了GMSGeocoder界面,只能通过它的API完成反向地理编码。

7 个答案:

答案 0 :(得分:16)

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

    task.resume()
}

答案 1 :(得分:5)

不,Google Maps SDK for iOS中没有原生方式。

这是一个非常受欢迎的功能请求,请参阅: Issue 5170: Feature request: Forward geocoding (from address to coordinates)

答案 2 :(得分:3)

如果您只是在寻找地理编码解决方案,您可以查看我构建的一个小型开源项目。它非常轻量级,使用名为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)!)
})

答案 3 :(得分:2)

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

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

答案 4 :(得分:1)

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

答案 5 :(得分:1)

Alamofire和Google's Geodecode API

快捷键4

func getAddressFromLatLong(latitude: Double, longitude : Double) {
    let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=YOUR_API_KEY_HERE"

    Alamofire.request(url).validate().responseJSON { response in
        switch response.result {
        case .success:

            let responseJson = response.result.value! as! NSDictionary

            if let results = responseJson.object(forKey: "results")! as? [NSDictionary] {
                if results.count > 0 {
                    if let addressComponents = results[0]["address_components"]! as? [NSDictionary] {
                        self.address = results[0]["formatted_address"] as? String
                        for component in addressComponents {
                            if let temp = component.object(forKey: "types") as? [String] {
                                if (temp[0] == "postal_code") {
                                    self.pincode = component["long_name"] as? String
                                }
                                if (temp[0] == "locality") {
                                    self.city = component["long_name"] as? String
                                }
                                if (temp[0] == "administrative_area_level_1") {
                                    self.state = component["long_name"] as? String
                                }
                                if (temp[0] == "country") {
                                    self.country = component["long_name"] as? String
                                }
                            }
                        }
                    }
                }
            }
        case .failure(let error):
            print(error)
        }
    }
}

答案 6 :(得分:0)

Google Maps API iOS SDK中没有原生方式。正如其他答案中所提到的,它是requested feature for years

要记住的一点是,Google Maps API主要专注于制作地图:这是主要目标。

您必须使用基于URL的API调用或其他一些服务。例如,一个名为SmartyStreets的不同服务有一个iOS SDK,它支持前向地理编码。这是来自their iOS SDK documentation page的Swift的示例代码:

// 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工作过。