2009-09-05 123 views

回答

107

,你所要做的就是建立一个CLLocationManager会找到你当前坐标。使用当前坐标,您需要使用MKReverseGeoCoder来查找您的位置。

- (void)viewDidLoad 
{ 
    // this creates the CCLocationManager that will find your current location 
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease]; 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; 
    [locationManager startUpdatingLocation]; 
} 

// this delegate is called when the app successfully finds your current location 
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    // this creates a MKReverseGeocoder to find a placemark using the found coordinates 
    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; 
    geoCoder.delegate = self; 
    [geoCoder start]; 
} 

// this delegate method is called if an error occurs in locating your current location 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
NSLog(@"locationManager:%@ didFailWithError:%@", manager, error); 
} 

// this delegate is called when the reverseGeocoder finds a placemark 
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark 
{ 
    MKPlacemark * myPlacemark = placemark; 
    // with the placemark you can now retrieve the city name 
    NSString *city = [myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey]; 
} 

// this delegate is called when the reversegeocoder fails to find a placemark 
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error 
{ 
    NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error); 
} 
+9

一记:你有藏匿位置管理器在一个ivar(也许一旦你收到一个位置,可能再次停止),否则它会立即autoreleased,你将不会收到任何代表回调。另外,反向地理编码器需要互联网连接才能正常工作。 – uliwitness 2011-02-23 17:19:47

+0

你能说我如何打印标题和副标题上的当前城市或位置吗? – Raju 2012-08-27 05:36:58

+1

@Frade #import Jonathan 2013-01-10 03:03:10

-10

阅读MKReverseGeocoder的文档 - 文档,指南& Apple提供的示例应用程序是有原因的。

+2

MKReverseGeoCoder已被弃用 – Marc 2012-04-04 16:35:09

2

您必须获取用户的当前位置,然后使用MKReverseGeocoder识别城市。

iPhone App Programming Guide第8章中有很好的例子。 一旦你有位置初始化地理编码器,设置代理并从地标读取国家。阅读MKReverseGeocodeDelegate文档和创建方法:

  • reverseGeocoder:didFindPlacemark:
  • reverseGeocoder:didFailWithError:

    MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; 
    geocoder.delegate = self; 
    [geocoder start]; 
    
+0

弃用...... – 2013-06-19 07:29:43

122

从iOS 5起MKReverseGeoCoder已弃用!

所以你想使用CLGeocoderCLLocationManager,非常简单,并与块一起工作。

例子:

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
      fromLocation:(CLLocation *)oldLocation 
{ 
    [self.locationManager stopUpdatingLocation]; 

    CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; 
    [geoCoder reverseGeocodeLocation:newLocation 
        completionHandler:^(NSArray *placemarks, NSError *error) { 
         for (CLPlacemark *placemark in placemarks) { 
          .... = [placemark locality]; 
         } 
        }]; 
} 

编辑:一个for in循环相反的,你也可以这样做:

NSString *locString = placemarks.count ? [placemarks.firstObject locality] : @"Not Found"; 
16

如果有人试图从MKReverseGeocoder移动到CLGeocoder然后我写一个博客文章,可能会有所帮助http://jonathanfield.me/jons-blog/clgeocoder-example.html

基本上,一个例子是,在创建locationManager和CLGeocoder对象后,只需将此代码添加到viewDidLoad(),然后制作一些标签或文本区域以显示数据。

[super viewDidLoad]; 
    locationManager.delegate = self; 
    [locationManager startUpdatingLocation]; 

    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; 
    [self.CLGeocoder reverseGeocodeLocation: locationManager.location completionHandler: 
    ^(NSArray *placemarks, NSError *error) { 


     CLPlacemark *placemark = [placemarks objectAtIndex:0]; 


      isoCountryCode.text = placemark.ISOcountryCode; 
      country.text = placemark.country; 
      postalCode.text= placemark.postalCode; 
      adminArea.text=placemark.administrativeArea; 
      subAdminArea.text=placemark.subAdministrativeArea; 
      locality.text=placemark.locality; 
      subLocality.text=placemark.subLocality; 
      thoroughfare.text=placemark.thoroughfare; 
      subThoroughfare.text=placemark.subThoroughfare; 
      //region.text=placemark.region; 



    }]; 
+0

将崩溃,如果空 – Marc 2012-04-17 15:22:41

+0

@macayer是的,*会*崩溃如果是空的,但如果我理解正确,则永远不会为空。将包含1个或更多元素或者是'nil',并且发送到'nil'的消息导致'nil',以及通过'nil'通过点符号访问属性。话虽如此,我们应该经常检查'错误'是不是'非'。 – 2013-05-08 11:52:53

28

这是对我工作的罚款:

CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; 
[geocoder reverseGeocodeLocation:self.locationManager.location 
       completionHandler:^(NSArray *placemarks, NSError *error) { 
        NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); 

        if (error){ 
         NSLog(@"Geocode failed with error: %@", error); 
         return; 

        } 


        CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

        NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode); 
        NSLog(@"placemark.country %@",placemark.country); 
        NSLog(@"placemark.postalCode %@",placemark.postalCode); 
        NSLog(@"placemark.administrativeArea %@",placemark.administrativeArea); 
        NSLog(@"placemark.locality %@",placemark.locality); 
        NSLog(@"placemark.subLocality %@",placemark.subLocality); 
        NSLog(@"placemark.subThoroughfare %@",placemark.subThoroughfare); 

       }]; 
+0

为什么它返回一个数组?奇怪。不管怎么说,还是要谢谢你。 – 2013-08-21 19:00:47

+0

这是光滑的,爱情块。我会放置地标数组的条件,以确保实际存在objectatindex:0。 – capikaw 2014-01-15 21:35:52

+4

你好,我收到错误'kCLErrorDomain错误8'你知道为什么吗? – maxisme 2014-04-19 20:16:47

1

您可以使用此代码获取当前城市: -

扩展YourController:CLLocationManagerDelegate { FUNC的LocationManager(经理:CLLocationManager ,didUpdateLocations位置:[CLLocation]) {

CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in 

     if (error != nil) 
     { 
      manager.stopUpdatingLocation() 
      return 
     } 
     else 
     { 
      if placemarks!.count > 0 
      { 
       let placeMarksArrray: NSArray = placemarks! 
       let pm = placeMarksArrray[0] as! CLPlacemark 
       self.displayLocationInfo(pm) 
       manager.stopUpdatingLocation() 
      } else 
      { 
       print("Problem with the data received from geocoder") 
      } 
     } 
    }) 
} 

func displayLocationInfo(placemark: CLPlacemark!) { 
    if (placemark != nil) { 
     //stop updating location to save battery life 
     locationLocation.stopUpdatingLocation() 
     var tempString : String = "" 
     if(placemark.locality != nil){ 
      tempString = tempString + placemark.locality! + " " 
      print(placemark.locality) 
     } 
     if(placemark.postalCode != nil){ 
      tempString = tempString + placemark.postalCode! + " " 
      print(placemark.postalCode) 
     } 
     if(placemark.administrativeArea != nil){ 
      tempString = tempString + placemark.administrativeArea! + " " 
      print(placemark.administrativeArea) 
     } 
     if(placemark.country != nil){ 
      tempString = tempString + placemark.country! + " " 



     } 
     let dictForaddress = placemark.addressDictionary as! NSDictionary 


     if let city = dictForaddress["City"] { 
      print(city) 



     } 
     strLocation = tempString 
    } 
} 
0
// place the function code below in desire location in program. 

// [self getCurrentLocation]; 



-(void)getCurrentLocation 
{ 
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; 
    [geocoder reverseGeocodeLocation:self->locationManager.location 
        completionHandler:^(NSArray *placemarks, NSError *error) { 
         NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); 

         if (error){ 
          NSLog(@"Geocode failed with error: %@", error); 
          return; 

         } 


         CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

         NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode); 
         NSLog(@"placemark.country %@",placemark.country); 
         NSLog(@"placemark.locality %@",placemark.locality); 
         NSLog(@"placemark.postalCode %@",placemark.postalCode); 
         NSLog(@"placemark.administrativeArea %@",placemark.administrativeArea); 
         NSLog(@"placemark.locality %@",placemark.locality); 
         NSLog(@"placemark.subLocality %@",placemark.subLocality); 
         NSLog(@"placemark.subThoroughfare %@",placemark.subThoroughfare); 

        }]; 
} 
3

如果有人需要它斯威夫特3,我这是怎么做的:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    let location = locations.first! 
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500) 

    self.location = location 
    self.locationManager?.stopUpdatingLocation() 

    // Drop a pin at user's Current Location 
    let myAnnotation: MKPointAnnotation = CustomPointAnnotation() 
    myAnnotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) 
    myAnnotation.title = "Localização" 
    self.mapViewMK.addAnnotation(myAnnotation) 

    self.mapViewMK.setRegion(coordinateRegion, animated: true) 
    self.locationManager?.stopUpdatingLocation() 
    self.locationManager = nil 

    // Get user's current location name 
    let geocoder = CLGeocoder() 
    geocoder.reverseGeocodeLocation(self.location!) { (placemarksArray, error) in 

     if (placemarksArray?.count)! > 0 { 

      let placemark = placemarksArray?.first 
      let number = placemark!.subThoroughfare 
      let bairro = placemark!.subLocality 
      let street = placemark!.thoroughfare 

      self.addressLabel.text = "\(street!), \(number!) - \(bairro!)" 
     } 
    } 
} 
相关问题