how to get the client/user location details

2.8k views Asked by At

In my application I want to track the client/user location to store in database. I'm using this code to get the user IP Address

 string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
        ipAddress = VisitorsIPAddr;

Using above code I'm getting the IP address. now the next step to get the timezone, Region, City Name, Country Name, Country Code, Weather Station, ISP etc.

But, I don't want to use any other third party API to get the details except Google. Anyone can reply to get my problem solved.

Is this possible to get the above details in asp.net using c# or I have to use any other service for that.

Using the IP I want to get the precise location of client address.

Details like http://www.iplocationtools.com/index.html

2

There are 2 answers

8
kaho On

Yes, sure, Google Maps JS API v3 does provide an IP to location geocoding services. You can use this code to get the users location based on their IP address:

// If ClientLocation was filled in by the loader, use that info instead
if (google.loader.ClientLocation) {
  zoom = 13;
  latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
  location = "Showing IP-based location: <b>" + getFormattedLocation() + "</b>";
}

Beside Lat/Lng, google.loader.ClientLocation returns an address which include city, country, country_code, region etc...
Also, look at the example here.

Even if the address is null, you can always use the returned Lat/Lng with the Geocoding Service to get the address detail.

However, just as it is mentioned in the official site:

... we don't recommend using this approach (using IP addresses to detect a user's location) for geolocation. The W3C approach is the easiest and most fully-supported so it should be prioritized over other methods.

Also in the issue tracker:

... We stopped documenting it several years ago and have recommended the HTML-based solutions due to their improved accuracy, but the functionality itself has not been removed from the Loader...

The best way to do this is with the HTML5-based approach. However, if you are using the IP-based, be sure that you realize Google can drop support to it really any time.

1
Musakkhir Sayyed On

You can use geoIP MaxMind web services to get location details in C#. Here is the following link which may be helpful for you.

http://dev.maxmind.com/geoip/geoip2/web-services/

Here is the Github repository available.

https://github.com/maxmind/GeoIP2-dotnet