[第1章]地图:CoreLocation的使用——CLGeocoder

来源:互联网 发布:网络安全法二十四条 编辑:程序博客网 时间:2024/06/09 20:56

关于CLGeocoder

官方文档:
The CLGeocoder class provides services for converting between a coordinate (specified as a latitude and longitude) and the user-friendly representation of that coordinate. A user-friendly representation of the coordinate typically consists of the street, city, state, and country information corresponding to the given location, but it may also contain a relevant point of interest, landmarks, or other identifying information. A geocoder object is a single-shot object that works with a network-based service to look up placemark information for its specified coordinate value.

解析:在“坐标(经纬度)”和“这个坐标所对应的详细信息”之间互相转换。例如,坐标:+23.15811500,+113.35156400 <——> 所对应的详细信息有:广东省广州市华南农业大学


使用CLGeocoder

1、引入包

import CoreLocation

2、geocode

方法原型(三个方法效果一样)

官方文档: After initiating a reverse-geocoding request, do not attempt to initiate another reverse- or forward-geocoding request.
Do not start a geocoding request at a time when the user will not see the results immediately. For example, do not start a request if your application is inactive or in the background.

解析:不要同时调用超过两次下列的任意方法。

// 地址是字典类型。func geocodeAddressDictionary(addressDictionary: [NSObject : AnyObject]!, completionHandler: CLGeocodeCompletionHandler!)
// 地址是字符串。func geocodeAddressString(addressString: String!, completionHandler: CLGeocodeCompletionHandler!)
// 比上面的方法多了一个CLRegion参数,用于优化查询结果。func geocodeAddressString(addressString: String!, inRegion region: CLRegion!, completionHandler: CLGeocodeCompletionHandler!)

闭包

上面三个方法的handler。

// geocoding handler, CLPlacemarks are provided in order of most confident to least confidenttypealias CLGeocodeCompletionHandler = ([AnyObject]!, NSError!) -> Void

小代码

// 实例化。var coder = CLGeocoder()// 查看字符串“Taishan”所对应的详细信息。coder.geocodeAddressString("Taishan", completionHandler: { (placemarks: [AnyObject]!, err: NSError!) -> Void in         // 返回值可能为nil。    if err != nil && placemarks == nil{        println(err)    }else {        // 输出查询结果数目。        println("count: \(placemarks.count)")        // 遍历。        for placemark in placemarks {            var temp = placemark as! CLPlacemark            println(temp.name)            println(temp.location)        }    }})

结果

Taishan


3、reverseGeocode

方法原型

func reverseGeocodeLocation(location: CLLocation!, completionHandler: CLGeocodeCompletionHandler!)

小代码

// 实例化一个CLLocation。(北京:39.908796, 116.417198)var placemark = CLLocation(latitude: 39.908796, longitude: 116.417198)coder.reverseGeocodeLocation(placemark, completionHandler: { (placemarks: [AnyObject]!, err: NSError!) -> Void in    if err != nil && placemarks == nil{        println(err)    }else {        //经测试,只包含一个CLPlacemark实例,不必遍历。        var placemark = placemarks.first as! CLPlacemark        println(placemark.locality)        println(placemark.location)    }})

结果

beijing


0 0