April 29, 2011

Find Web visitor’s Location Automatically with Google APIs

This works great in the United States and has mixed results elsewhere. I’m working to see if I can change that. If your primary customer base is in the US, use this confidently. If your primary customer base is elsewhere, use in development stage only.

Google provides IP address to location translation for FREE! Whenever you use Google’s jsapi script to dynamically load a Google AJAX API, Google automatically populates google.loader.ClientLocation, which has all the juicy details about the web visitor’s location.

We can also add this to SharePoint Portal in Content Editor web part.

Script :

<DIV id='info'> </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('info').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon +   '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
      document.getElementById('info').innerHTML = '<p>Whoops!</p>';
}

</script>