Is it possible to programatically distinguish between American and Canadian phone numbers?
Asked Answered
Z

1

10

I'm using this bit of code (in Groovy, but it should be pretty clear what it does)

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

Running mobileNumberUtilService.getISOCountryCode('<internationalized American or Canadian number>') returns [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].

Is there any way to distinguish those, short of some sort of web service lookup?

Zaxis answered 30/10, 2013 at 12:40 Comment(0)
N
10

Take a look at the geocoder subproject of libphonenumber. It provides a PhoneNumberOfflineGeocoder that does exactly what you're looking for:

@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"
Nationalist answered 30/10, 2013 at 14:29 Comment(3)
Super helpful, thanks. What I actually wanted was the ISO code.Zaxis
It looks like you can get the ISO code from PhoneNumberUtil.getRegionCodeForNumber().Nationalist
I was actually coming back to post that I'd found this out :) I don't know how I missed that. It's right there in the JavaDocs.Zaxis

© 2022 - 2024 — McMap. All rights reserved.