如何在iOS中通过经纬度识别时区

问题描述 投票:0回答:4

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

objective-c ios5 latitude-longitude nstimezone
4个回答
12
投票

我试过

APTimeZones
图书馆。在我的例子中,我需要时区以及来自特定城市经纬度的国家/地区名称。 我浏览了图书馆以了解它是如何工作的。它实际上有一个 JSON 格式的文件,其中包含所有时区及其相应的经纬度。它需要经纬度作为输入并循环遍历此 JSON 文件,比较所有时区经纬度与输入经纬度的距离。它返回距离输入经纬度最短的时区。

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

所以 Apple 的原生框架在这种情况下非常好。

下面的代码对我很有效。

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

}];

在 Swift 中

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

2
投票

这是对我有用的技巧。可以从中提取时区标识符,您可以将此 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); 

    }];

1
投票

我已经将 DarkSky 的时区代码移植到 Swift,它使用准确的时区形状来生成一个简化的时区数据库,允许快速查找和小尺寸。

APTimeZones
是缺乏的,因为它只是在寻找具有最近中心的时区。

https://github.com/bialylis/tz-lookup-oss


0
投票

我创建了另一个库来将坐标解析为时区和国家。 https://github.com/patrick-zippenfenig/SwiftTimeZoneLookup

时区数据库嵌入为一个包(~5 MB)。我刚刚更新了时区边界生成器的最新版本2023b

用法:

import SwiftTimeZoneLookup


let database = try SwiftTimeZoneLookup()
guard let timezone = database.simple(latitude: 47.5, longitude: 8.6) else {
  fatalError("Timezone not found, coordinates invalid?")
}
print(timezone) // "Europe/Zurich"


guard let lookup = database.lookup(latitude: 47.5, longitude: 8.6) else {
  fatalError("Timezone not found, coordinates invalid?")
}
print(lookup) // SwiftTimeZoneLookupResult(timezone: "Europe/Zurich", countryName: Optional("Switzerland"), countryAlpha2: Optional("CH"))
© www.soinside.com 2019 - 2024. All rights reserved.