samedi 25 novembre 2017

Getting current user location in ASP.NET Web App

I am creating a simple ASP.NET web app that shows user's current location on Google maps with Embed Api. I am trying to implement it by using IP Address of user to get coord by using this online rest api:

http://ift.tt/2A5jDAn]

The coords are not accurate. Here's the Default.cs code:

    public partial class _Default : Page
{
    private const String API_KEY = "/*KEY_HERE*/";
    private String url = "http://ift.tt/1lj6Mbe" + API_KEY;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string ipAddress = new WebClient().DownloadString("http://ift.tt/1ExhLr8");
            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("http://ift.tt/1ExhLr8");
        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;
    }
}

Here is SimpleIp Class:

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

Here is IpInfo Class:

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

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




Aucun commentaire:

Enregistrer un commentaire