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

Reading time: About 3 minutes

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.

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.

1
<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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!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>. :)

46 comments skip to comment form

  1. FokusLop said— 15 hours later

    Good article, Thanks. my name Philip.

    #1
  2. Mike Mella said— 2 days later

    Your demo page link seems to be broken.

    #2
  3. Paul said— 2 days later

    Nice! Cheers for the tip, off to abuse it ;-)

    #3
  4. Brian Cray said— 2 days later

    MIKE MELLA: Just tested and it works fine for me… please explain the error?

    #4
  5. Mike Mella said— 2 days later

    When I click the demo link, I just see the word “Whoops!”

    #5
  6. Bill said— 2 days later

    I see Whoops too.

    #6
  7. Brian Cray said— 2 days later

    Strange… Perhaps it needs a window.load event to let the google script load fully. Will change soon

    #7
  8. Bill said— 2 days later

    Nearby tweets couldn’t find anything either, but putting my location in manually did.

    #8
  9. Richard said— 3 days later

    I get whoops too. I’m located in UAE

    #9
  10. Desi Blog said— 3 days later

    Hey there got “whoops”. Located in Dubai,UAE. Love the idea of the script..hope u can find out why its coming..

    #10
  11. Stephen Cronin said— 3 days later

    It works fine for me, pretty accurate too.

    There are various free server side solutions out there. I use IP2C for most of my projects.

    Where this method would be good is in situations where you don’t have access to the server side. For example on Blogger or WordPress.com.

    Nice find, Thanks.

    #11
  12. Ash said— 3 days later

    While this looks good, it isn’t the most accurate due to the way IP addresses are allocated.

    This said I was in Lancashire… 282 miles from Bournemouth :Z

    #12
  13. Ayush said— 3 days later

    Hi this is nice.. is there any way i can get the location on email as well, instead of just showing it to the user.. I am not too much into coding so unable to make out if this is possible.. thanks.. Ayush

    #13
  14. Brian Cray said— 3 days later

    I know this is pretty accurate in USA and it seems to have some inaccuracies in Europe. Apparently in some other places Google can’t translate the IP address to a location at all. I’ll see what I can dig up about this…

    #14
  15. Russell said— 3 days later

    Very Cool! Thanks for making this available.

    #15
  16. Bill said— 3 days later

    More information: It worked at work, but not at home (Comcast)

    #16
  17. N GowriSankar said— 4 days later

    It works like charm. I tried it from Bangalore, India. I also tested it by connecting by VPN to our client site and then it displayed it as “Dallas, Tx” :) .

    Thanks for sharing this.

    #17
  18. jQuery Tutorials said— 4 days later

    I wrote another article on Geolocation and jQuery the other month and I guess users will be interested in how to get location by IP Address using jQuery and geolocation web service.

    #18
  19. Justin said— 1 week later

    Great little spippit Brian, I’ll be looking to do some location based work soon and was going to referance a DB – Why bother when Google does all the hard work eh?

    #19
  20. cms webmaster said— 1 week later

    Coool, it is working ;-)

    #20
  21. HB said— 1 week later

    I get “whoops” too, and “sorry” on Nearby Tweets. Some restrictions may apply, I guess.

    #21
  22. sandepp said— 3 weeks later

    Good Coool, n working
    Thanks google

    #22
  23. Myfacefriends said— 1 month later

    I get “whoops”

    thanks for this information!

    #23
  24. Gercek said— 1 month later

    This is a great tutorial. However, if you’re in a VPN, it will not work.

    #24
  25. Joshua Heiland said— 1 month later

    I spent a good full day looking for a way to do this last year – I was never able to figure it out. I have big plans for this :) Thanks Brian

    #25
  26. Rahul said— 1 month later

    Helloo
    this artice is gud
    but i m luking for something else
    i working on google map in flASH AND I REQUIRED LOATION OF EACH AREA (SCHOOL. COFFESHOP, HOSPITAL ,, anyhting between the route )
    is tat possible
    can u help me out with some gud solution for the same

    #26
  27. hermawan75 said— 2 months later

    Hello

    Many thanks for article

    From,
    Hermawan, Indonesia

    #27
  28. cancel bubble said— 2 months later

    Another “Whoops!” here.

    #28
  29. Adam Roessler said— 2 months later

    Great article, Brian! This will certainly help my attempt to provide content specific to my visitors’ region. However, as a newbie to js, I’m wondering if you can point me in the right direction to complete my endeavor. I would like to use visitor_region variable to determine what page the visitor will see, or be redirected to. Any ideas or places I should look to learn this? Thanks for getting me started!

    #29
  30. Bony Yousuf said— 2 months later

    thanks man……

    #30
  31. vzagkid said— 3 months later

    I am getting Woops. For me it is not working.
    Will This API work within the US?.
    is there any way to find the client location by client ip.
    Please let me know the way if exist.

    Thanks in Advance.

    #31
  32. directory said— 3 months later

    look nice thanks :)

    just testing in my domain http://www.chandan.in/maps

    #32
  33. Hari Krishnan said— 5 months later

    It works great. Thanks to google and to you……

    #33
  34. Mike O'Reilly said— 5 months later

    Hi Brian,

    This is ithe full text of the whoops page…

    Whoops!

    Array ( [HTTP_ACCEPT] => image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/x-silverlight, application/x-shockwave-flash, */* [HTTP_REFERER] => http://briancray.com/2009/05/29/find-web-visitors-location-javascript-google-api/ [HTTP_ACCEPT_LANGUAGE] => en-ie,rs1_0ebf3d2786e;q=0.8,rs2_344f7a430db;q=0.5,rs3_c412d9ea0d;q=0.3 [HTTP_USER_AGENT] => Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; MS-RTC LM 8; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) [HTTP_ACCEPT_ENCODING] => gzip, deflate [HTTP_HOST] => briancray.com [HTTP_CONNECTION] => Keep-Alive [HTTP_COOKIE] => _bsau=12559622564534827528; _bsas=12559622564538355538; __utma=115403349.740199543.1255962257.1255962257.1255962257.1; __utmb=115403349.1.10.1255962257; __utmc=115403349; __utmz=115403349.1255962257.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=find%20by%20location%20and%20item%20javascript [PATH] => /sbin:/usr/sbin:/bin:/usr/bin [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.2.3 (CentOS) [SERVER_NAME] => briancray.com [SERVER_ADDR] => 70.32.84.110 [SERVER_PORT] => 80 [REMOTE_ADDR] => 86.40.233.78 [DOCUMENT_ROOT] => /var/www/vhosts/briancray.com/httpdocs [SERVER_ADMIN] => bcrayzie@gmail.com [SCRIPT_FILENAME] => /var/www/vhosts/briancray.com/httpdocs/tests/getlocation/getlocation.html [REMOTE_PORT] => 56697 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /tests/getlocation/getlocation.html [SCRIPT_NAME] => /tests/getlocation/getlocation.html [PHP_SELF] => /tests/getlocation/getlocation.html [REQUEST_TIME] => 1255962317 )

    #34
  35. Peter said— 6 months later

    Great post! Although I get Whoops on your test link.

    But shouldn’t it be possible to display at least the IP with google.loader.ClientLocation?

    Could anybody submit a screenshot of a successful IP tracking?

    BTW I live in Germany and I think that Google has us off the maps.

    #35
  36. jignesh said— 6 months later

    hi i got “whoops”

    #36
  37. foxy said— 6 months later

    stop using Windows and IE and won’t have wooops

    #37
  38. Sriraj said— 7 months later

    i get a “woops” when i try it form my work but it works fine when i try it form home. The only thing i can think of is different isp [in both cases i am using DHCP]
    i tried on IE, firefox and safari and got same result so i guess this has nothing to do with windows or IE

    #38
  39. Dina said— 7 months later

    Thank you for your tutorial.

    #39
  40. MC said— 9 months later

    I get “whoops”

    Why can’t it show the lat and lng ?

    Thanks for your attention.

    MC

    #40
  41. Dustin Fisher said— 9 months later

    Thanks for the post and code. It helped me out with a post I did on personalization for eCommerce sites.

    #41
  42. bo said— 9 months later

    I got whoops too.. on my pc..
    strange, I tested on my mobile and it works….

    #42
  43. Derek said— on May 29, 2009 later

    I love Google!

    #43
  44. jacob said— on May 29, 2009 later

    whoops on firefox

    #44
  45. satyam said— on May 29, 2009 later

    whoops only

    #45
  46. Vipin Vijayan said— on May 29, 2009 later

    I too get Whooooooooops!!!!
    I think this is because google failed to identify client location….
    I had created a new key for using google API and tried,

    Try this link,
    http://www.fortunesys.com/clientinfo.htm
    Please inform me if you got work this.
    mailto: vipin.vjayan@gmail.com

    #46
  47. Respond to this post—

Return to navigation
591