获取ASP.NET Web App中的当前用户位置

时间:2017-11-25 11:09:22

标签: asp.net web geolocation location maps

我正在创建一个简单的ASP.NET网络应用,通过嵌入式Api显示用户在Google地图上的当前位置。 我试图通过使用用户的IP地址来实现它,通过使用这个在线休息api获得协调:

http://ip-api.com/json/[IP_ADDRESS_HERE]

指标不准确。 这是Default.cs代码:

    public partial class _Default : Page
{
    private const String API_KEY = "/*KEY_HERE*/";
    private String url = "https://www.google.com/maps/embed/v1/place?key=" + API_KEY;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string ipAddress = new WebClient().DownloadString("https://api.ipify.org?format=json");
            SimpleIp simpleIp = JsonConvert.DeserializeObject<SimpleIp>(ipAddress);
            IpInfo ipInfo = GetUserLocationDetailsyByIp(simpleIp.Ip);
            String latLongData = "&q=" + ipInfo.Longitude + "," + ipInfo.Latitude;
            mapFrame.Attributes.Add("src", url + latLongData);
            logLocation.Text = simpleIp.Ip + " -- " + latLongData;
        }
    }

    protected void currentLoactionButton_Click(object sender, EventArgs e)
    {
        string ipAddress = new WebClient().DownloadString("https://api.ipify.org?format=json");
        SimpleIp simpleIp = JsonConvert.DeserializeObject<SimpleIp>(ipAddress);
        IpInfo ipInfo = GetUserLocationDetailsyByIp(simpleIp.Ip);
        String latLongData = "&q=" + ipInfo.Longitude + "," + ipInfo.Latitude;
        mapFrame.Attributes.Add("src", url + latLongData);
        logLocation.Text = simpleIp.Ip + " -- " + latLongData;
    }

    private IpInfo GetUserLocationDetailsyByIp(string ip)
    {
        var ipInfo = new IpInfo();
        try
        {
            var info = new WebClient().DownloadString("http://ip-api.com/json/" + ip);
            ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
        }
        catch (Exception ex)
        {
            logLocation.Text = ex.ToString();
        }

        return ipInfo;
    }
}

这是SimpleIp Class:

public class SimpleIp
{
    [JsonProperty("ip")]
    public string Ip { get; set; }
}

这是IpInfo类:

public class IpInfo
{
    [JsonProperty("lat")]
    public string Longitude { get; set; }

    [JsonProperty("lon")]
    public string Latitude { get; set; }
}

0 个答案:

没有答案