Quick and reliable way to get location information about your users.

[UPDATE: Nov 12, 2009]  Posted a quick demo of this working.

Just wanted to post this more for myself than anything else.  The problem is this:

You want to know where your users are coming from.  More specifically, you want their latitude and longitude, city, state, and country.  Now I know there are a lot of ways to get this info using free or paid web services, databases, and even loading map api’s.  But here’s a really dirt simple way to get at that info without much effort.

  1. Grab a reference to Google’s API loader
       1: <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  2. Once the script is loaded you have access to some methods to get you the info you want.  In particular the “ClientLocation” object off of  google.loader. Here I’m assigning the location information to some inputs on a form.
       1: if (google.loader.ClientLocation) {
       2:             var loc = google.loader.ClientLocation;
       3:             if (loc.address) {
       4:                 $('#City').val(loc.address.city);
       5:                 $('#Region').val(loc.address.region);
       6:                 $('#Country').val(loc.address.country);
       7:                 $('#CountryCode').val(loc.address.country_code);                
       8:             } 
      10:             if (loc.latitude) {
      11:                 $('#Lat').val(loc.latitude);
      12:                 $('#Lon').val(loc.longitude);
      13:             }
      14:         }
    Taken from the Google website:
    • When an application makes use of the AJAX API loader, the loader attempts to geo locate the client based on it's IP address. If this process succeeds, the client's location, scoped to the metro level, is made available in the google.loader.ClientLocation property. If the process fails to find a match, this property is set to null.
    • When populated, the google.loader.ClientLocation object is populated with the following metro-level granularity properties:

      • ClientLocation.latitude — supplies the low resolution latitude associated with the client's IP address
      • ClientLocation.longitude — supplies the low resolution longitude associated with the client's IP address
      • ClientLocation.address.city — supplies the name of the city associated with the client's IP address
      • ClientLocation.address.country — supplies the name of the country associated with the client's IP address
      • ClientLocation.address.country_code — supplies the name of the ISO 3166-1 country code associated with the client's IP address
      • ClientLocation.address.region — supplies the country specific region name associated with the client's IP address
  3. Sit back and relax as you solved your problem in a matter of seconds and a few short lines of code.
kick it on DotNetKicks.com
Bookmark and Share
blog comments powered by Disqus
  • Menu

  • Tags