【问题标题】:How to get the Current city in iOS如何在 iOS 中获取当前城市
【发布时间】:2017-07-17 15:54:50
【问题描述】:

我想将城市名称发送到服务器。我正在使用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];
}

【问题讨论】:

  • 您必须使用 Google 还是 Apple 解决方案可以?
  • 我使用google api进行反向地理编码
  • 是的,我看到了,但你使用它吗?
  • 我尝试使用 CLGeocoder 但它没有返回任何城市。大多数属性都为 null 这就是我使用 google api 的原因

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


【解决方案1】:

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

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
 }];

【讨论】:

    【解决方案2】:

    在 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)
                }
    
            })
    
    
    
    
    
    }
    

    【讨论】:

    • 我试过了,但我无法获得城市名称。你能检查我的更新部分吗
    • 只需将此代码转换为目标 c 它对我来说完美工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多