2009-09-05 85 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!)" 
     } 
    } 
} 
相關問題