Brian Cray ··· Home > Blog > Javascript > Find web visitor's location automatically with javascript and Google APIs

Find web visitor's location automatically with javascript and Google APIs

What if you could automatically identify where your website visitors came from? Imagine the possibilities of serving web visitors locale–specific information without the slightest effort on their part. Now that's what I call usability, accessibility, and pure marketing awesomeness all wrapped in one package.

This tutorial finds a web visitor's location based on their IP address. Keep in mind that IP to location translation isn't an exact science. After all, would you want the websites you visit to be able to find your exact home address? That's a scary thought.

What this tutorial will do is at least provide an idea of a visitor's exact city (in most cases). You also get the visitor's approximated latitude and longitude, as well as his or her's state, country, and country code.

If you're the type who likes to take apart source code, skip the tutorial and see a sample with source code.

Who provides IP address to location translation for FREE!?

Google does. 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.

Surprised? It's a little known (and badass) fact.

Step 1: Load the Google AJAX API script

If you haven't already, signup for a free Google API key.

Simply including the following jsapi script gives you the web visitor's location details in google.loader.ClientLocation.

<script type="text/javascript" src="http://www.google.com/jsapi?key=API_KEY_GOES_HERE"></script>

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

Add this javascript inside its own <script type="text/javascript"> tag to extract the web visitor's location details 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
}

Step 3: Put it all together in a webpage

Here's a sample webpage that displays the user's location. Try it out!

<!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>

That's all you have to do!

Can you believe it is that simple? I can't believe I'm giving this information gold mine away so freely!

It's time to use your imagination and put this information to use! Take it a step further with the Google Maps API and read my article How to calculate distance with Javascript and Google Maps API! Be creative and have fun! I did when I used it to create <revealsecrets>Nearby Tweets</revealsecrets>. :)

Update June 1, 2009: 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.