Phonegap - the best way to discover the country iso code from a user

家住魔仙堡 提交于 2019-12-03 17:33:47

Are you looking for where the user is at the moment or for something more like the users language/nationallity? For the latter you could always look at what's in navigator.language. Depending on target platform it'll give you either just language code ('en' on my Android test machine) or language code and country code ('en-us' on my iOS test machine). To see what it will give you, go with your device's stock browser here and type in navigator.language in the text input box.

Otherwise, casual browsing of the HTML5 Geolocation spec seems to indicate that you'll either need a web-service or package a datafile with codes in the app. This seems to be a pretty good one.

I found navigator.language sometimes only gave me the language and not the locale (eg "en" rather than "en-gb"). To solve this in android I created a new java class in src/com called DeviceCulture.java with this code:

package com;
import java.util.Locale;

public class DeviceCulture {

    public String get() {
        try{            
            return Locale.getDefault().toString();//get the locale from the Android Device      
        }catch(Exception e){
            return "";
        }   
    }
}

Then add this before the super.loadUrl line in /src/com/phonegap/YOUR_APP/App.java

DeviceCulture deviceCulture = new DeviceCulture();
appView.addJavascriptInterface(deviceCulture , "DeviceCulture");

Then in your javascript use this to get the locale (eg "en_GB")

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