How to Find and Display visitor's location with Javascript and Google API in Easy Steps

This script will find out visitor's exact city (in most cases). You also get the visitor's latitude and longitude, as well as state, country, and country code.

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 contains the web visitor's location.

Step 1: Load the Google AJAX API script

First you need 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=your-api-key"></script>
 

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

Retrieve location information as code below:

 
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
{
    // error
}
 

Step 3: Run it in a webpage

Here's a sample webpage that displays the user's location.

 
<!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=your-api-key"></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>error!</p>';
        }
    </script>
    </body>
</html>