是否有可能以编程方式区分美国和加拿大的电话号码?

时间:2013-10-30 12:40:44

标签: grails groovy libphonenumber

我正在使用这段代码(在Groovy中,但应该很清楚它的作用)

class MobileNumberUtilService {
def getISOCountryCode(rawNumber) {
    def phoneNumberUtil = PhoneNumberUtil.getInstance()
    def number

    try {
        number = phoneNumberUtil.findNumbers(rawNumber, null).iterator().next().number()
    } catch (NoSuchElementException exception) {
        return ''
    }

    CountryCodeToRegionCodeMap.countryCodeToRegionCodeMap[number.countryCode].first()
}
}

正在运行mobileNumberUtilService.getISOCountryCode('<internationalized American or Canadian number>')会返回[US, AG, AI, AS, BB, BM, BS, CA, DM, DO, GD, GU, JM, KN, KY, LC, MP, MS, PR, SX, TC, TT, VC, VG, VI]

有没有办法区分那些,缺少某种Web服务查找?

1 个答案:

答案 0 :(得分:6)

看一下libphonenumber的地理编码器子项目。它提供的PhoneNumberOfflineGeocoder可以完全满足您的需求:

@Grapes([
  @Grab('com.googlecode.libphonenumber:libphonenumber:5.8'),
  @Grab('com.googlecode.libphonenumber:geocoder:2.9')
])

import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder

def phoneNumberUtil = PhoneNumberUtil.instance
def geocoder = PhoneNumberOfflineGeocoder.instance
def usaNum = phoneNumberUtil.parse("1-406-750-9999", "US")
def canNum = phoneNumberUtil.parse("1-416-750-9999", "US")

assert geocoder.getCountryNameForNumber(usaNum, Locale.default) ==
    "United States"
assert geocoder.getCountryNameForNumber(canNum, Locale.default) ==
    "Canada"