Search code examples
javascriptasp.netgoogle-mapsgeolocationlatitude-longitude

How to get Geo location from the WebURL


  • I have create one ASP.NET website and Hosted it on the server.
  • Suppose My web access URL is "www.xyz.com".
  • Now I want the Geo Location who access my website and display it on the Google Map. Or can I get the latitude or longitude from where this Web-URL is access ?

So, is this possible ?


Solution

  • This is HTML CODE

    <asp:GridView ID="gridView1" runat="server" AutoGenerateColumns = "false">
        <Columns>
            <asp:BoundField DataField="IPAddress" HeaderText="IP Address" />
            <asp:BoundField DataField="CountryName" HeaderText="Country" />    
            <asp:BoundField DataField="Latitude" HeaderText="Latitude" />
            <asp:BoundField DataField="Longitude" HeaderText="Latitude" />
        </Columns>
    </asp:GridView>
    

    This is C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ipAddress))
        {
            ipAddress = Request.ServerVariables["REMOTE_ADDR"];
        }
    
        string APIKey = "<Your API Key>";
        string url = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKey, ipAddress);
        using (WebClient client = new WebClient())
        {
            string json = client.DownloadString(url);
            Location location = new JavaScriptSerializer().Deserialize<Location>(json);
            List<Location> locations = new List<Location>();
            locations.Add(location);
            gridView1.DataSource = locations;
            gridView1.DataBind();
        }
    }
    
    
    public class Location
    {
        public string IPAddress { get; set; }
        public string CountryName { get; set; }      
        public string Latitude { get; set; }
        public string Longitude { get; set; }       
    }