如何在C#中获取用户的国家/地区名称?

时间:2012-01-17 16:02:45

标签: c# javascript jquery html5 geolocation

我目前正在使用地理位置来获取用户的国家/地区名称。这是我的代码:

navigator.geolocation.getCurrentPosition(function (pos) {
    var latlng = pos.coords.latitude + "," + pos.coords.longitude;
    var apiurl = 'http://maps.google.com/maps/geo?output=json&sensor=false&q=' + latlng;
    var yqlqry = encodeURIComponent('select * from json where url="' + apiurl + '"');
    var yqlurl = 'http://query.yahooapis.com/v1/public/yql?q=' + yqlqry + '&format=json&callback=?';
    $.getJSON(yqlurl, function (data) {
        var countryName = data.query.results.json.Placemark.AddressDetails.Country.CountryName;
        var newCountryName = countryName.toLowerCase();
        if (newCountryName == "united states")
            newCountryName = "us";
        else if (newCountryName == "england" || newCountryName == "ireland" || newCountryName == "scotland" || newCountryName == "wales" || newCountryName == "northern ireland")
            newCountryName = "uk";
        else if (newCountryName == "australia")
            newCountryName = "au";
        else if (newCountryName == "canada")
            newCountryName = "ca";
        else
            newCountryName = "world";
        $('a[title = "' + newCountryName + '"]').trigger('click');
    });
});

我宁愿在服务器端使用一些东西。有谁知道你是否可以在C#中获得用户的国家名称?

4 个答案:

答案 0 :(得分:3)

在服务器端,您唯一可以回复的是IP地址,您可以使用该地址执行位置查找。有IP地址到位置映射的免费数据库,或者您可以使用HostIP.info。

请查看https://stackoverflow.com/questions/372591/how-to-get-city-country-and-country-code-for-a-particular-ip-address-in-asp-ne以获取更多信息。

答案 1 :(得分:0)

我为WP7做了这个,但是在standard.net框架中代码几乎相同:http://www.felicepollano.com/2012/01/11/AnImplementationOfICivicAddressResolverForWP7.aspx 做这项工作的班级如下。只需删除作为WP7依赖项的ICivicAddressResolver并创建自己的界面。

 public class AddressResolver:ICivicAddressResolver
    {
        string language = "en-GB";
        public AddressResolver()
        {

        }
        public AddressResolver(string language)
        {
            this.language = language;
        }
        [DataContract]
        public class AddressInfo
        {
            [DataMember(Name = "formatted_address")]
            public string FormattedAddress { get; set; }
        }
        [DataContract]
        public class ResultInfo
        {
            [DataMember(Name = "results")]
            public AddressInfo[] Info { get; set; }
        }
        readonly string URITemplate = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=true&language={2}";
        #region ICivicAddressResolver Members

        public CivicAddress ResolveAddress(GeoCoordinate coordinate)
        {
            throw new NotImplementedException("Use async version instead");
        }

        public void ResolveAddressAsync(GeoCoordinate coordinate)
        {
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            client.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    var ainfo = ReadToObject<ResultInfo>(e.Result);
                    ResolveAddressCompleted(this, new ResolveAddressCompletedEventArgs(ToCivic(ainfo),e.Error,false,null));
                }
                else
                {
                    ResolveAddressCompleted(this, new ResolveAddressCompletedEventArgs(new CivicAddress(), e.Error, false, null));
                }
            };
            client.DownloadStringAsync(new Uri(GetFormattedUri(coordinate)));
        }

        private CivicAddress ToCivic(ResultInfo ainfo)
        {
            List<string> res = new List<string>();
            foreach (var single in ainfo.Info)
            {
                res.Add(single.FormattedAddress);
            }
            if (res.Count > 0)
                return new CivicAddress() { AddressLine1 = res[0] };
            else
                return new CivicAddress() { AddressLine1 = "#UNKNOWN#" };
        }

        public event EventHandler<ResolveAddressCompletedEventArgs> ResolveAddressCompleted = delegate { };

        #endregion
        private string GetFormattedUri(GeoCoordinate coord)
        {
            return string.Format(CultureInfo.InvariantCulture, URITemplate, coord.Latitude, coord.Longitude,language);
        }
        public static T ReadToObject<T>(string json) where T : class
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            T res = ser.ReadObject(ms) as T;
            ms.Close();
            return res;
        }
    }

答案 2 :(得分:0)

为什么不试试IP2Location的API?

你可以像这样传递你的ipaddress。

http://api.ip2location.com/?ip=145.228.219.221&key=demo

的更多信息

http://www.ip2location.com/ip-country-web-service.aspx

答案 3 :(得分:-1)

不知道这是否有帮助,但在本地

CultureInfo.CurrentCulture.Name

根据您当前的区域设置返回类似“en-GB”或“fr-FR”的内容