Thursday, July 14, 2011

How to Determine The Visitor's City, State, Province & Country Automatically with Javascript using Google APIs - Get your Visitors Location with Javascript

If you need to get your visitor's city, state, province & country using javascript, you can do that by using Google APIs. Its very easy to do with a few lines of code and can provide a lot of possibilities because you can determine your visitors location with javascript. You can set your site's language, timezone, or design according to your visitors location. Here are the instructions:


1. Load the Google AJAX API script:
<script type="text/javascript" src="http://www.google.com/jsapi?key=API_KEY_GOES_HERE"></script>

2. Extract the visitor's location from google.loader.ClientLocation

if(google.loader.ClientLocation)
{
 visitor_lat = google.loader.ClientLocation.latitude;
 visitor_lon = google.loader.ClientLocation.longitude;
 visitor_city = google.loader.ClientLocation.address.city;
 visitor_region = google.loader.ClientLocation.address.region;
 visitor_country = google.loader.ClientLocation.address.country;
 visitor_countrycode = google.loader.ClientLocation.address.country_code;
}
else
{
 // ClientLocation not found or not populated
 // so perform error handling
}

3. Put it all together in a webpage
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
 <head>
  <title>Get web visitor's location</title>
  <meta name="robots" value="none" />
 </head>
 <body>
 <div id="yourinfo"></div>
 <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
 <script type="text/javascript">
  if(google.loader.ClientLocation)
  {
   visitor_lat = google.loader.ClientLocation.latitude;
   visitor_lon = google.loader.ClientLocation.longitude;
   visitor_city = google.loader.ClientLocation.address.city;
   visitor_region = google.loader.ClientLocation.address.region;
   visitor_country = google.loader.ClientLocation.address.country;
   visitor_countrycode = google.loader.ClientLocation.address.country_code;
   document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
  }
  else
  {
   document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
  }
 </script>
 </body>
</html>
There you go, it's that simple. You can try out the code here. Credit goes to Brian Cray, more explanation about his script on his blog.

No comments:

Post a Comment