在iOS中从纬度和经度获取位置名称

18

我想通过经纬度查找当前位置名称,

这是我尝试的代码片段,但我的日志显示除了placemarkplacemark.ISOcountryCodeplacemark.country以外所有地方都是null值

我想要placemark.localityplacemark.subLocality的值,但它显示为空值。

- (void)viewWillAppear:(BOOL)animated
{
     [super viewWillAppear:animated];

    // this creates the CCLocationManager that will find your current location
    locationManager = [[CLLocationManager alloc] init];
    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
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:locationManager.location
                   completionHandler:^(NSArray *placemarks, NSError *error) {
                       NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");

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

                       }

                       NSLog(@"placemarks=%@",[placemarks objectAtIndex:0]);
                       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);

                   }];
}

// 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);
}

提前致谢。

编辑:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
        NSLog(@"longitude = %.8f\nlatitude = %.8f", currentLocation.coordinate.longitude,currentLocation.coordinate.latitude);

    // stop updating location in order to save battery power
    [locationManager stopUpdatingLocation];


    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
         if (error == nil && [placemarks count] > 0)
         {
             CLPlacemark *placemark = [placemarks lastObject];

             // strAdd -> take bydefault value nil
             NSString *strAdd = nil;

             if ([placemark.subThoroughfare length] != 0)
                 strAdd = placemark.subThoroughfare;

             if ([placemark.thoroughfare length] != 0)
             {
                 // strAdd -> store value of current location
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]];
                 else
                 {
                     // strAdd -> store only this value,which is not null
                     strAdd = placemark.thoroughfare;
                 }
             }

             if ([placemark.postalCode length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]];
                 else
                     strAdd = placemark.postalCode;
             }

             if ([placemark.locality length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]];
                 else
                     strAdd = placemark.locality;
             }

             if ([placemark.administrativeArea length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]];
                 else
                     strAdd = placemark.administrativeArea;
             }

             if ([placemark.country length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]];
                 else
                     strAdd = placemark.country;
             }
         }
     }];
}

2
你需要使用一些第三方API,例如Google Places API - Navnath Godse
1
不需要使用Google的付费服务 - 这个功能已经内置在iOS中了。看一下CLLocation和CLPlacemark。它将为您提供任何您想要的坐标粒度,例如国家、城市、地区、时区等等。 - samiles
12个回答

14

我给你一个片段,用于解析地址。我在必要的地方包含了注释以便你理解代码。除此之外,如果你还有任何问题无法理解,请随时询问。

didUpdateToLocation方法中编写以下片段。

NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil)
    NSLog(@"longitude = %.8f\nlatitude = %.8f", currentLocation.coordinate.longitude,currentLocation.coordinate.latitude);

// stop updating location in order to save battery power
[locationManager stopUpdatingLocation];


// Reverse Geocoding
NSLog(@"Resolving the Address");

// “reverseGeocodeLocation” method to translate the locate data into a human-readable address.

// The reason for using "completionHandler" ----
   //  Instead of using delegate to provide feedback, the CLGeocoder uses “block” to deal with the response. By using block, you do not need to write a separate method. Just provide the code inline to execute after the geocoding call completes.

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
 {
    NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
    if (error == nil && [placemarks count] > 0)
    {
        placemark = [placemarks lastObject];

        // strAdd -> take bydefault value nil
        NSString *strAdd = nil;

        if ([placemark.subThoroughfare length] != 0)
            strAdd = placemark.subThoroughfare;

        if ([placemark.thoroughfare length] != 0)
        {
            // strAdd -> store value of current location
            if ([strAdd length] != 0)
                strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]];
            else
            {
            // strAdd -> store only this value,which is not null
                strAdd = placemark.thoroughfare;
            }
        }

        if ([placemark.postalCode length] != 0)
        {
            if ([strAdd length] != 0)
                strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]];
            else
                strAdd = placemark.postalCode;
        }

        if ([placemark.locality length] != 0)
        {
            if ([strAdd length] != 0)
                strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]];
            else
                strAdd = placemark.locality;
        }

        if ([placemark.administrativeArea length] != 0)
        {
            if ([strAdd length] != 0)
                strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]];
            else
                strAdd = placemark.administrativeArea;
        }

        if ([placemark.country length] != 0)
        {
            if ([strAdd length] != 0)
                strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]];
            else
                strAdd = placemark.country;
        }

使用地理位置,strAdd将返回地址。

享受编程!


当前位置未知。 - Krunal
当前位置是从该方法中的新位置。请检查我的更新答案。 - Niru Mukund Shah
嘿,我已经为你完成了所有工作。你只需要用我的代码替换 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 中的你的代码,就能得到答案了。 - Niru Mukund Shah
1
我遇到了错误,类似于在NSAraay中找不到“placemarks.subThoroughfare”。 - Krunal
你误解了,伙计,在示例中并不是这样的。我在你的代码片段中遇到了错误。我只是给了你另一个苹果的例子,它也没有显示城市名字。 - Krunal
显示剩余10条评论

11

带有完成块的方法:

typedef void(^addressCompletion)(NSString *);

-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletion)completionBlock
{
    __block CLPlacemark* placemark;
    __block NSString *address = nil;

    CLGeocoder* geocoder = [CLGeocoder new];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (error == nil && [placemarks count] > 0)
         {
             placemark = [placemarks lastObject];
             address = [NSString stringWithFormat:@"%@, %@ %@", placemark.name, placemark.postalCode, placemark.locality];
             completionBlock(address);
         }
     }];
}

这是使用它的方法:

CLLocation* eventLocation = [[CLLocation alloc] initWithLatitude:_latitude longitude:_longitude];

[self getAddressFromLocation:eventLocation complationBlock:^(NSString * address) {
        if(address) {
            _address = address;
        }
    }];

8

我在Swift 3中实现了Niru的解决方案,如果有需要的人在此发布:

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!)"
    }
}

2

这不是免费的API。 - Rushi trivedi

0
在Swift 4.1和Xcode 9.4.1中,这是我的一个解决方案。我在这里使用< strong>地理编码 API来获取完整地址。通过这个API,我还可以获取村庄名称。

我正在使用< strong>reverseGeocodeLocation,但它没有获取到村庄地址详细信息或村庄名称,只获取了附近城市的名称。 这是最好的解决方案之一...

func getAddressForLatLng(latitude: String, longitude: String)  { // Call this function

     let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)")//Here pass your latitude, longitude
     print(url!)
     let data = NSData(contentsOf: url! as URL)

     if data != nil {
        let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
        print(json)

        let status = json["status"] as! String
        if status == "OK" {

            if let result = json["results"] as? NSArray   {

                if result.count > 0 {
                    if let addresss:NSDictionary = result[0] as? NSDictionary {
                        if let address = addresss["address_components"] as? NSArray {
                            var newaddress = ""
                            var number = ""
                            var street = ""
                            var city = ""
                            var state = ""
                            var zip = ""
                            var country = ""

                            if(address.count > 1) {
                                number =  (address.object(at: 0) as! NSDictionary)["short_name"] as! String
                            }
                            if(address.count > 2) {
                                street = (address.object(at: 1) as! NSDictionary)["short_name"] as! String
                            }
                            if(address.count > 3) {
                                city = (address.object(at: 2) as! NSDictionary)["short_name"] as! String
                            }
                            if(address.count > 4) {
                                state = (address.object(at: 4) as! NSDictionary)["short_name"] as! String
                            }
                            if(address.count > 6) {
                                zip =  (address.object(at: 6) as! NSDictionary)["short_name"] as! String
                            }
                            newaddress = "\(number) \(street), \(city), \(state) \(zip)"
                            print(newaddress)

                            // OR 
                            //This is second type to fetch pincode, country, state like this type of data

                            for i in 0..<address.count {
                                print(((address.object(at: i) as! NSDictionary)["types"] as! Array)[0])
                                if ((address.object(at: i) as! NSDictionary)["types"] as! Array)[0] == "postal_code" {
                                    zip =  (address.object(at: i) as! NSDictionary)["short_name"] as! String
                                }
                                if ((address.object(at: i) as! NSDictionary)["types"] as! Array)[0] == "country" {
                                    country =  (address.object(at: i) as! NSDictionary)["long_name"] as! String
                                }
                                if ((address.object(at: i) as! NSDictionary)["types"] as! Array)[0] == "administrative_area_level_1" {
                                    state =  (address.object(at: i) as! NSDictionary)["long_name"] as! String
                                }
                                if ((address.object(at: i) as! NSDictionary)["types"] as! Array)[0] == "administrative_area_level_2" {
                                    district =  (address.object(at: i) as! NSDictionary)["long_name"] as! String
                                }

                            }

                        }

                    }
                }

            }

        }

    }

}

调用此函数的方式如下

self.getAddressForLatLng(latitude: "\(self.lat!)", longitude: "\(self.lng!)")

0

试试这个

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        //..NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            lblgetaddrees.text = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@",
                                  placemark.subThoroughfare, placemark.thoroughfare,
                                  placemark.postalCode, placemark.locality,
                                  placemark.administrativeArea,
                                  placemark.country];
        } else {
            //..NSLog(@"%@", error.debugDescription);
        }
    } ];

0
首先,在didUpdateToLocation中过滤位置,以防止使用缓存或错误的位置进行地理编码。
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

if (abs(locationAge) > 5.0) return;

if (newLocation.horizontalAccuracy < 0) return;

另外,尝试将reverseGeoCoding方法从didUpdateToLocation中移开


苹果演示样例也显示了空值,为什么呢?有任何想法吗? http://developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011097 - Krunal

0

0

一旦您获得了位置的纬度经度值,您可以使用CLGeocoder。这里有一个教程可能会对您有所帮助。


它可以用于iOS 5及以上版本。 - Deepesh Gairola
苹果演示样例也显示了空值,为什么呢?有任何想法吗? http://developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011097 - Krunal
苹果演示样例也显示了空值,为什么呢?有任何想法吗? http://developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011097 - Krunal
你是在模拟器上尝试吗?如果是,请在设备上尝试。 - Deepesh Gairola

0

苹果演示样例也显示了空值,为什么呢?有任何想法吗? http://developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011097 - Krunal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接