如何在iOS中获得当前城市

时间:2017-02-27 06:10:17

标签: ios google-maps-api-3 cllocationmanager

我想将城市名称发送到服务器。我使用CLLocationManager获得纬度经度。然后我使用此链接进行反向地理编码。

https://maps.googleapis.com/maps/api/geocode/json?latlng=lati,longi&key=myApiKey

我的问题是针对不同的位置,地址组件的数量是不同的。例如,我正在获取当前位置的这一组地址组件。

"results": [
    {
        "address_components": [
            {
                "long_name": "ABC Rd", 
                "short_name": "ABC Rd", 
                "types": [
                    "route"
                ]
            }, 
            {
                "long_name": "My City", 
                "short_name": "My City", 
                "types": [
                    "administrative_area_level_2", 
                    "political"
                ]
            }, 
            {
                "long_name": "My Province", 
                "short_name": "AB", 
                "types": [
                    "administrative_area_level_1", 
                    "political"
                ]
            }, 
            {
                "long_name": "My Country", 
                "short_name": "MC", 
                "types": [
                    "country", 
                    "political"
                ]
            }
        ], 

为我的客户提供此位置

results": [
    {
        "address_components": [
            {
                "long_name": "4", 
                "short_name": "4", 
                "types": [
                    "street_number"
                ]
            }, 
            {
                "long_name": "some name", 
                "short_name": "some name", 
                "types": [
                    "route"
                ]
            }, 
            {
                "long_name": "some name", 
                "short_name": "Some name", 
                "types": [
                    "political", 
                    "sublocality", 
                    "sublocality_level_2"
                ]
            }, 
            {
                "long_name": "some name", 
                "short_name": "some name", 
                "types": [
                    "political", 
                    "sublocality", 
                    "sublocality_level_1"
                ]
            }, 
            {
                "long_name": "city", 
                "short_name": "city", 
                "types": [
                    "locality", 
                    "political"
                ]
            }, 
            {
                "long_name": "some name", 
                "short_name": "Some name", 
                "types": [
                    "administrative_area_level_1", 
                    "political"
                ]
            }, 
            {
                "long_name": "Client country", 
                "short_name": "CC", 
                "types": [
                    "country", 
                    "political"
                ]
            }, 
            {
                "long_name": "12345", 
                "short_name": "12345", 
                "types": [
                    "postal_code"
                ]
            }
        ], 

当地址组件不同时,如何获取不同位置的确切城市名称。首先,我尝试将其作为组件索引号,但由于组件数量不同,我无法做到这一点。什么是正确的方法呢?请帮我。 感谢

更新

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

        placemark = [placemarks objectAtIndex:0];

        NSString *address = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
                             placemark.subThoroughfare, placemark.thoroughfare,
                             placemark.postalCode, placemark.subLocality,
                             placemark.subAdministrativeArea,
                            placemark.country];

       // NSString *address=[self.placemark];

        NSDictionary *dictAddress = [NSDictionary dictionaryWithDictionary:placemark.addressDictionary];
        NSMutableDictionary *dictTxtData = [NSMutableDictionary dictionary];
        NSLog(@"----LOCATION NAME----%@",[placemark.addressDictionary valueForKey:@"Name"]);
        NSLog(@"-----STREET ADDRESS---%@",[placemark.addressDictionary valueForKey:@"Thoroughfare"]);
        NSLog(@"-----CITY-----%@",[placemark.addressDictionary valueForKey:@"City"]);



        strCountry=placemark.country;

        NSLog(@"Address------%@",address);
    } else {
        NSLog(@"%@", error.debugDescription);
    }
} ];

结果我

----LOCATION NAME----My Rd
-----STREET ADDRESS---My Rd
-----CITY-----(null)
Address------(null) My Rd
(null) (null)
(null)
My Country

这就是我调用位置更新的方式

-(void)GetLocationData
 {
   if (self.locationManager == nil)
   {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
}
else
{
    nil;
}

if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
{
    [self.locationManager requestWhenInUseAuthorization];
}
else
{
    nil;
}

self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;//kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}

2 个答案:

答案 0 :(得分:1)

Google API的json响应可能包含不同的地点标记,具体取决于位置。使用索引不是正确的方法。您可以在类型为locality的json组件中找到城市名称。以下是代码段

NSDictionary *locationData = [[json objectForKey:@"results"] objectAtIndex:0];
NSArray* addressComponents= [locationData objectForKey:@"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
   for (NSDictionary* address in addressComponents)
    {
        NSArray* addressType = [address objectForKey:@"types"];
       NSString* firstType = [addressType objectAtIndex:0];
       if([firstType isEqualToString:@"locality"])
           cityName = [address objectForKey:@"long_name"];
}

或者您也可以在iOS中使用CLGeocoder API。

CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lat longitude:long];

[ceo reverseGeocodeLocation: loc completionHandler:
 ^(NSArray *placemarks, NSError *error) {
     CLPlacemark *placemark = [placemarks objectAtIndex:0];
     NSLog(@"placemark %@",placemark.locality); // Get the city name
 }];

答案 1 :(得分:0)

在viewdidload方法中调用setLocation()

func setLocation()
{

    // self.view.backgroundColor = UIColor.whiteColor()
    self.edgesForExtendedLayout = .None

    // Set bounds to inner-west Sydney Australia.



    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()



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

    //        print("dofo \(manager.location?.coordinate.latitude)")
    //        print(manager.location?.coordinate.longitude)



        currentlat = (manager.location?.coordinate.latitude)!
        cuurentlong = (manager.location?.coordinate.longitude)!




        let geoCoder = CLGeocoder()
        let location = CLLocation(latitude: currentlat,
                                  longitude: cuurentlong)
        geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

            // Place details
            var placeMark: CLPlacemark!
            placeMark = placemarks?[0]

            // Address dictionary
            print(placeMark.addressDictionary)

            // Location name
            if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
                print(locationName)
            }

            // Street address
            if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
                print(street)
            }

            // City
            if let city = placeMark.addressDictionary!["City"] as? NSString {
                print(city)
            }

            // Zip code
            if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
                print(zip)
            }

            // Country
            if let country = placeMark.addressDictionary!["Country"] as? NSString {
                print(country)
            }

        })





}