【问题标题】:How do you get a user's country name in C#?如何在 C# 中获取用户的国家/地区名称?
【发布时间】:2012-01-17 16:02:45
【问题描述】:

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

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# 中获取用户的国家/地区名称?

【问题讨论】:

  • 在 C# 中发出相同的请求 - 获取您从导航器的 GeoAPI 获得的位置并将其转发到服务器上您自己的 Web 服务,该服务器使用 WebClient 类发出 Get 请求
  • 我想向您指出,爱尔兰不在英国。北爱尔兰是,但爱尔兰是爱尔兰共和国,它本身就是一个国家。

标签: c# javascript jquery html geolocation


【解决方案1】:

在服务器端,您唯一可以回复的是 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 了解更多信息。

【讨论】:

    【解决方案2】:

    我为 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;
            }
        }
    

    【讨论】:

      【解决方案3】:

      为什么不试试 IP2Location 的 API 呢?

      你可以像这样传递你的IP地址。

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

      更多信息在

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

      【讨论】:

        【解决方案4】:

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

        CultureInfo.CurrentCulture.Name
        

        根据您当前的语言环境返回类似“en-GB”或“fr-FR”的内容

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-09
          相关资源
          最近更新 更多