How to identify timezone from longitude and latitude in iOS

房东的猫 提交于 2019-12-28 06:44:07

问题


How can I find out which NSTimeZone a given longitude and latitude fall in?


回答1:


I have tried APTimeZones library. In my case I needed Timezone as well as country name from the lat long of a particular city. I went through the library to know how it works. It actually has a file in JSON format which has all the timezones along with their corresponding lat longs. it takes the lat long as input and loops through this JSON file comparing the distances of all the timezone's lat long from the input lat long. It returns the time zone which has shortest distance from the input lat long.

But the problem was for a city in the border of a big country, it returned me the timezone of neighbouring country, as I also extracted the country code from it, I got the neighbouring country.

So Apple's native framework is far good in this case.

And the below code worked for me well.

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

}];

In 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:


See https://github.com/Alterplay/APTimeZones, it uses a predefined local database of Timezones.




回答3:


Here is the trick that worked for me. From which timezone identifier can be extracted and you can use this id for timezone.

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

    }];


来源:https://stackoverflow.com/questions/9188871/how-to-identify-timezone-from-longitude-and-latitude-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!