【问题标题】:Using GMSAddress and GMSGeocoder to return Coordinates from Address in Swift在 Swift 中使用 GMSAddress 和 GMSGeocoder 从地址返回坐标
【发布时间】:2015-02-17 08:40:43
【问题描述】:

有没有办法在 iOS Swift 中使用 GMS 从输入的地址字符串中获取坐标?我可以找到从坐标返回地址的示例(反向地理编码?),但不是相反。谷歌提供这项服务吗?首先解析输入的地址字符串,返回最合适的实际地址,最后返回坐标。请提供一个简单的例子,或者指出我正确的方向。问候,克里斯

【问题讨论】:

    标签: ios swift geocoding reverse-geocoding


    【解决方案1】:

    自 2015 年 6 月起,GMS iOS SDK 不再直接公开此功能。但是,有两种方法可以得到它。第一个是使用 Google Maps Web API。

    let baseURLGeocode = "https://maps.googleapis.com/maps/api/geocode/json?"
    
    func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
    
        if let lookupAddress = address {
    
            var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
            geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    
            let geocodeURL = NSURL(string: geocodeURLString)
    
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
    
                var error: NSError?
                let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<NSObject, AnyObject>
    
                if (error != nil) {
                    println(error)
                    completionHandler(status: "", success: false)
                }
                else {
                    // Get the response status.
                    let status = dictionary["status"] as String
    
                    if status == "OK" {
                        let allResults = dictionary["results"] as Array<Dictionary<NSObject, AnyObject>>
                        self.lookupAddressResults = allResults[0]
    
                        // Keep the most important values.
                        self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as String
                        let geometry = self.lookupAddressResults["geometry"] as Dictionary<NSObject, AnyObject>
                        self.fetchedAddressLongitude = ((geometry["location"] as Dictionary<NSObject, AnyObject>)["lng"] as NSNumber).doubleValue
                        self.fetchedAddressLatitude = ((geometry["location"] as Dictionary<NSObject, AnyObject>)["lat"] as NSNumber).doubleValue
    
                        completionHandler(status: status, success: true)
                    }
                    else {
                        completionHandler(status: status, success: false)
                    }
                }
            })
        }
        else {
            completionHandler(status: "No valid address.", success: false)
        }
    }
    

    你可以在这里找到这个方法的完整描述:http://www.appcoda.com/google-maps-api-tutorial/

    第二种方法是使用苹果原生的CoreLocation框架

    func geoLocate(address:String!){
    let gc:CLGeocoder = CLGeocoder()
    
    gc.geocodeAddressString(address, completionHandler: { (placemarks: [AnyObject]!, error: NSError!) -> Void in
        let pm = placemarks as! [CLPlacemark]
        if (placemarks.count > 0){
            let p = pm[0]
    
            var myLatitude = p.location.coordinate.latitude
            var myLongtitude = p.location.coordinate.longitude
    
            //do your stuff
        }
    })
    }
    

    编辑:Swift 4.2

    func geoLocate(address:String!){
            let gc:CLGeocoder = CLGeocoder()
            gc.geocodeAddressString(address) { (placemarks, error) in
                if ((placemarks?.count)! > 0){
                    let p = placemarks![0]
                    print("Lat: \(p.location?.coordinate.latitude) Lon: \(p.location?.coordinate.longitude)")
                }
    
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2014-09-02
      相关资源
      最近更新 更多