10

如何找出给定的经度和纬度属于哪个 NSTimeZone?

4

2 回答 2

11

我试过APTimeZones图书馆。就我而言,我需要时区以及来自特定城市纬度的国家名称。我通过图书馆了解它是如何工作的。它实际上有一个 JSON 格式的文件,其中包含所有时区及其相应的经纬度。它将 lat long 作为输入并循环通过此 JSON 文件,比较所有时区的 lat long 与输入 lat long 的距离。它返回与输入 lat long 距离最短的时区。

但问题是对于一个大国边境的城市,它返回给我邻国的时区,因为我也从中提取了国家代码,我得到了邻国。

所以苹果的原生框架在这种情况下要好得多。

下面的代码对我很有效。

CLLocation *location = [[CLLocation alloc] initWithLatitude:your_latitude longitude:your_longitude];
CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
[geoCoder reverseGeocodeLocation: location completionHandler:^(NSArray *placemarks, NSError *error)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"Timezone -%@",placemark.timeZone);

//And to get country name simply.
NSLog(@"Country -%@",placemark.country);

}];

在斯威夫特

let location = CLLocation(latitude: your_latitude, longitude: your_longitude)
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(location) { (placemarks, err) in
     if let placemark = placemarks?[0] {
          print(placemark.timeZone)
          print(placemark.country)
     }
}
于 2016-06-20T06:10:10.237 回答
1

这是对我有用的技巧。可以从中提取时区标识符,您可以将此 id 用于时区。

CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

[geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {

    if (error == nil && [placemarks count] > 0) {

        placeMark = [placemarks lastObject];
         NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"identifier = \"[a-z]*\\/[a-z]*_*[a-z]*\"" options:NSRegularExpressionCaseInsensitive error:NULL];
        NSTextCheckingResult *newSearchString = [regex firstMatchInString:[placeMark description] options:0 range:NSMakeRange(0, [placeMark.description length])];
        NSString *substr = [placeMark.description substringWithRange:newSearchString.range];
        NSLog(@"timezone id %@",substr); 

    }];
于 2014-11-21T05:17:48.560 回答