如何本地化来自reverseGeocodeLocation的地址结果?

26

我的iPhone应用程序应该基于用户的纬度和经度解析地址。 reverseGeocodeLocation运行正常,但结果是英文。

有没有一种方法将结果本地化为其他语言?

在苹果或其他任何地方都找不到相关信息。

我使用的代码是:

CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
CLLocation *location = [[[CLLocation alloc] 
       initWithLatitude:coord.latitude longitude:coord.longitude] autorelease];

[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
    NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");

    if (error){
        NSLog(@"Geocode failed with error: %@", error);
        [self displayError:error];
        return;
    }
    if(placemarks && placemarks.count > 0)
    {
      //do something
        CLPlacemark *topResult = [placemarks objectAtIndex:0];

        NSString *addressTxt = [NSString stringWithFormat:@"%@ %@,%@ %@", 
           [topResult subThoroughfare],[topResult thoroughfare],
           [topResult locality], [topResult administrativeArea]];
    }
}

2
CLGeocoder基于Google Geocoder,如果在URL参数中设置语言选项,则可以生成本地化结果。我使用Google API,并且返回的结果似乎是用其他语言本地化的。这可能很明显,但您是否将设备的语言设置为英语以外的其他内容?您还尝试过什么其他方法吗? - Jim
是的!更改语言后它起作用了,但问题仍然存在,是否可能强制结果为特定语言? - user513790
从文档来看,我不认为有这样的解决方案。如果几个小时内你还没有得到更详细的答案,我可以给你展示一些可能会帮助你的代码。不过我现在手头上没有它。 - Jim
@user513790,你是否找到如何强制结果显示特定语言的解决方案?对我们来说,它应该始终是英文。根据我的研究,似乎不可能实现。 - windfly2006
4个回答

13

我找到了如何本地化国家名称的方法,也许会有所帮助:

CLPlacemark *placemark;

NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: placemark.ISOcountryCode forKey: NSLocaleCountryCode]];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString *country = [usLocale displayNameForKey: NSLocaleIdentifier value: identifier];

请将任何国家的ID插入@"en_US"之处。


10
你知道我如何对placemark.locality执行相同的操作吗?例如:"Roma" -> "Rome"。 - Dodgson86

5

针对 Swift 4,iOS 11 的解决方案

您可以通过设置参数 preferredLocale: Locale.init(identifier: "en_US") 强制获取所选语言环境的地理编码结果。

CLGeocoder().reverseGeocodeLocation(location, preferredLocale: Locale.init(identifier: "en_US"), completionHandler: {(placemarks, error) -> Void in
    print(location)

    if error != nil {
        print("Reverse geocoder failed with error" + error!.localizedDescription)
        return
    }

    if placemarks!.count > 0 {
        let pm = placemarks![0]
        print(pm.administrativeArea!, pm.locality!)
    }
    else {
        print("Problem with the data received from geocoder")
    }
})

1

Mattt Thompson在他的网站NSHipster上,对使用AddressBookUI.framework中的一种方法本地化地址进行了很好的写作。他还在Github上有一个格式化库,其中包含一个用于执行此类型本地化的类,该类使用了他所描述的AddressBookUI.framework方法。


0

iOS11以后,苹果为我们提供了另一个API,可以设置语言环境以打印本地化语言。

- (void)reverseGeocodeLocation:(CLLocation *)location preferredLocale:(nullable NSLocale *)locale
 completionHandler:(CLGeocodeCompletionHandler)completionHandler API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接