Simple IP Geolocation Using Javascript and the Google AJAX Search API

Update 10/17/15 – Unfortunately it appears as though this is no longer working. If you’re able to get it to work, or if you have any further insight, please leave a comment below.

I recently started looking into IP geolocation/geotargeting for some projects. By “geolocation” or “geotargeting” I mean serving different content to users based upon their physical location as determined by their IP address. Now, as we all know IP addresses are far from perfect so the best you’re going to get seems to be ~80% accuracy. That said, there are still a lot of great things you can do for those people if you know where they are coming from.

An example for Detailed Image around holiday time would be showing different content to people who are past the safe cutoff date to receive a shipment before Christmas. For instance, on 12/21 a person in California might see an ad hyping up our gift certificates, while a visitor in New York would see an ad that they can still receive a ground shipment prior to Christmas.

And that’s just one example. I’m planning on doing some other things with geolocation for a future project, so I though it was time to finally figure out how I was going to do it.

And once I started looking into it I realized that the only way to do this with any kind of accuracy is to query a very large, actively maintained database of IP addresses and their corresponding locations. I narrowed it down to two options:

  • GeoLite City – a free downloadable database that is update monthly and claims to be 79% accurate to a city level (which is where I got the 80% number above). They also offer a premium version that’s slightly more accurate.
  • Google’s API, which maintains this database on their end for Google Maps and probably fifty other things that we don’t realize.

There are some definite advantages of having the GeoLite City database on your server, namely that you can query it on the server side prior to loading a page. To do this on any scale, however, you really shouldn’t install it as a MySQL database. Instead you should use their binary format and corresponding API.

This seems like an awful lot of work. Plus it requires that someone update the database monthly when new releases come out. Worth it for some people and some projects I’m sure. Not me though. I also don’t like using my resources when working on a project when I can use someone else’s resources, especially when it’s Google and it’s free and reliable.

So then I started digging into Google and I had a really, really hard time finding documentation. Finally I found this page with one example way down on the bottom, and with some common sense was able to use that to get what I needed.

In hopes of saving someone else some time, here’s a really simple way to implement IP geotargeting on your site in a few minutes. The simple function below gets all of the important info from Google (latitude, longitude, city, country, region) and writes it out to the page. What you do from there is up to your imagination!

Here’s all you have to do:

  1. Sign-up for an AJAX Search API Key
  2. Use the Javascript below, replacing YOURKEY with your actual key from Google
  3. That’s it! Check out a demo on my site.

Javascript:

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

<script type="text/javascript">

function geoTest() {

	if (google.loader.ClientLocation) {
		
		var latitude = google.loader.ClientLocation.latitude;
		var longitude = google.loader.ClientLocation.longitude;
		var city = google.loader.ClientLocation.address.city;
		var country = google.loader.ClientLocation.address.country;
		var country_code = google.loader.ClientLocation.address.country_code;
		var region = google.loader.ClientLocation.address.region;
	  
		var text = 'Your Location<br /><br />Latitude: ' + latitude + '<br />Longitude: ' + longitude + '<br />City: ' + city + '<br />Country: ' + country + '<br />Country Code: ' + country_code + '<br />Region: ' + region;
	
	} else {
		
		var text = 'Google was not able to detect your location';
	
	}
	
	document.write(text);

}

geoTest();

</script>

48 comments on Simple IP Geolocation Using Javascript and the Google AJAX Search API

  1. Josh says:

    Demo is not workin!!can u chk tht out

    • Adam McFarland says:

      Hi Josh – the demo works for me. What does it show for you? Could possibly be that Google cannot get your location based upon your IP…

      • Adam McFarland says:

        Made a slight adjustment to the code. It now will display text if it cannot retrieve your location…one of the things you’d need to have in place if you were to use this in a production environment.

  2. Rob says:

    Works for me 😀

  3. Anthony says:

    Yeah, geolocation is a very cool thing. Just be careful, though. Whether it’s Google or anyone else, APIs usually have limits (especially ones like this which are meant to be used heavily). Be sure to always read the terms carefully, and use the paid version of the API if you need to. The last thing you want is to reach visitor number 1,001 in a day and have the API begin spitting out results you didn’t expect.

    • Adam McFarland says:

      Definitely. I don’t plan on using this for any real application until some point in 2010, but I’ll be sure to read through all of the terms prior to starting development. Good practice for any API or service that you rely on heavily.

  4. Roger says:

    Hello Adam,

    Thanks for the info about GeoLite City. However, I have been investigating the Google Geolocation API, and unfortunately it requires every user to have google gears installed and the geolocation gear enabled, therefore using this would greatly reduce the number of users you would have using your site. I think a database, however out of date would support a greater number of users. Hopefully soon this will be a moot point as I think it is the intention of HTML 5 Specification to encourage browser developers to have geolocation switched on by default.

    Anyway, thanks for the info 🙂

    • Adam McFarland says:

      Roger –

      Thanks for reading. I think you’re looking at something different – try the demo on my site http://www.adammcfarland.com/demos/geolocation.php That works for me in every browser without Gears installed.

      P.S – just noticed the syntax highlighting isn’t working on the post, I’ll fix that today…

      • Adam McFarland says:

        Was in a bit of a rush this morning when I wrote that comment. I just fixed the syntax highlighting.

        I do agree that HTML 5 *could* solve the problem, but you’re still likely going to need a backup for the people who don’t enable it by default in their browser.

        One other thing about using GeoCity – performance when querying a huge info source like that can be a big deal. If you’re willing to utilize their binary format + API you can probably solve the problem, but if you just decide to install it as a massive MySQL database it will really slow down your server. That’s a much bigger downside to me (having any additional server load that you don’t need) as opposed to it being slightly out dated.

  5. Alex l says:

    I was not able to get your code to work?

    the code keeped coming up with “Google was not able to detect your location”. Any ideas on why.
    Also your demo and “http://www.adammcfarland.com/demos/geolocation.php” came up with the same display.

    :/

    • Adam McFarland says:

      Hi Alex. The demo is working for me. For one reason or another Google can’t get a location from your IP. Try browsing from another location or on another network.

  6. Roger says:

    Hello Adam,

    Since my last message back in March, I have tried the demo on doezens of pcs using chrome and IE and every time I get the “Google was not able to detect your location” message 🙁

    I was wondering, could it be an issue with me being in the UK?

    • Adam McFarland says:

      Thanks for the follow-up Roger. That’s unfortunate. It’s certainly possible that it’s a US only feature or that you have to do something differently to get it to work internationally. I’ve only tested it here in NY. It’s worked at multiple locations (home, work, etc). I haven’t used it in production yet, and I’m not sure I will with HTML5 geolocation available now.

      • Adam McFarland says:

        PS – I didn’t go back and read the old comments before that post. Interesting to see how my thoughts on HTML5 have changed a bit. I think it depends on your application – most of the time you want to get permission from your users, in which case HTML5 is ideal and supported across more and more browsers, especially mobile browsers. If you’re doing something simple like showing a different piece of text on a page to different users (say changing an estimated shipping delivery date based upon distance), then it makes sense to use another solution like this JS or a database.

        • It’s not I don’t think. I have never used your exact script here, but I’ve written my own that make use of the same API (which you now no longer have to sign up for) and they work the same as what you describe here. I’m outside the states.

  7. Enrico says:

    I just found this link by googling for a client side solution to show country based notice messages.
    The example page was very precise in locating my suburb in Sydney Australia. I don’t think it’s a US only feature, more likely that Roger is in the remaining 20% 🙂 thanks for the example

  8. Filip says:

    Work’s for me! I’m in Croatia, Osijek, and it pops up location like a charm! thx! 🙂

  9. ahmad Harb says:

    Hello Adam,

    Thanks for this article, but It’s not working !! google.loader.ClientLocation is null …
    even the demo page is not working it return “Google was not able to detect your location” …
    maybe google changed it’s API ?? OR my location is not supported ??

    • Adam McFarland says:

      Hi Ahmad –

      Looks like it’s not working for me either. It was working pretty recently – maybe it’s just temporarily down. You can check directly by going to http://www.google.com/jsapi (no API key is necessary anymore) and looking to see if google.loader.ClientLocation is not null. It would be disappointing if this no longer works because it was a nice simple option compared to others out there.

      – Adam

  10. Sanjib says:

    Can I get area with GeoLite City? Please Help

  11. Thank you for the great tutorial. I needed a simple way to detect a user’s country and this did exactly that without server-side programming, ip lookups, and databases. Keep up the good work 🙂

  12. UBe says:

    Hi Adam,
    I’m trying you example snippet code, but google.loader.ClientLocation is null. Event your demo return “Google was not able to detect your location” so I suppose this API doesn’t work anymore. Could you confirm that?

    Tnx.

    • Adam McFarland says:

      Hi UBe –

      I’m unable to get it to work for my location but in tests I’ve done it seems to work for some other locations, I’m not sure why it works for some spots and not others. As you can see from that comment above from 5/17 some people are still getting it to work for them. I’d avoid using it in any production environment unfortunately.

      – Adam

  13. Nice Script Adam. Unfortunately, I’m having issues as well. Works in some locations, but not in others. Google is not playing nice I guess.

    I do not want to slow my server with a massive binary file or MySQL DB. I’ve used GEOip but found the API to be very, very slow.

    I was considering MaxMind’s paid API (50,000 requests for $20). Do you know of any other solutions? HTML5 geolocation is overkill for my purposes. Thanks.

  14. Forgot to check “notify me of follow up comments”. Thanks.

    • Adam McFarland says:

      Hi Jason,

      Thanks for reading. Yea I’m not sure why it’s doing that. It’s unfortunate that Google with all of their geolocation data doesn’t have a simple API that works consistently.

      I don’t know of any really good solutions – I haven’t done much with geolocation lately. MaxMind looks pretty good, I glanced at their site quick. I do have an upcoming project where I want rough geolocation (at the state level) so I’d be interested in that as well if it works. If you like it let me know!

      If I come across any other interesting services or tools I’ll be sure to post them here in the comments as well.

      • I don’t really understand it either. Using the Google Map API is an option, but there are limited requests (unless you pay for Google Apps for Business) and the TOS specify you can only use the data to interact with a Google Map in some way.

        Since I posted my last comment I signed up for a test account with MaxMind and have been pleased thus far. They give 1,000 free queries during the test run. Buying the state level access cost $20 for 50,000 queries. Caching the location will cut down on queries.

        I’m happy with the performance speed. The entire site is downloading in 532ms today. My tests generally range between 450ms and 800ms, so virtually no change.

        I’m using the WP Geolocation plugin recommended on their third party script page. WordPress.org reports it hasn’t been updated in over two years, but I’ve tested with the newest version of WordPress and its working fine. It simply drops the MaxMind javascript into the head section and puts the returning info into javascript variables.

        My only issue with MaxMind is they are unreachable. I’ve tried to get in contact with via phone, contact form, and on Twitter and have had absolutely no response.

        That makes me hesitant to commit since my client is dependent on this data. But, I did read there is a ticketing system for paid customers that may have a better response.

        Again, thanks for the post. Very creative way to utilize the Google Search API. I didn’t see the API’s true potential previously. I plan to experiment with the API to see if Google is more apt to provide geo info in conjunction with other calls.

        Cheers

  15. wapdam musik says:

    Hi Thank for this api. But how about client which are connected from opera mini or ucweb browser? Those browser require HTTP_FORWARDED_FOR to detect real ip. But is there any solution to get real location for those user who are connected using proxy type browser?
    Using mysql database it can be solved easily but how about client side solution? Looking forward to hear from you.
    Thanks

    • Adam McFarland says:

      Hi Wapdam,

      Unfortunately I do not know of any other solutions beyond what’s written in the post and comments. You might want to check out the MaxMind option referenced above.

      – Adam

  16. redwap says:

    Maxmind is mysql based. It will consume high server load.

  17. Fahad says:

    Hi Adam,

    Its a great tutorial. I want only US from this code, but my only point is how do I test that client is in US because based on that I need to convert Exchange Rate.
    I am based in India.

    Little help will be appreciated.

    Thanks.
    – Fahad

    • Adam McFarland says:

      Hi Fahad,

      Thanks for reading. You can tell which country the user is in by either using the “country” or “country_code” variables in the demo. However, I would caution against using this in a production environment where you need anything close to 100% accuracy. As you can tell from the other comments, the demo works for some people and not for others with seemingly no pattern. If you need a high level of accuracy I’d advise looking at other solutions.

      – Adam

  18. Nafsheeh says:

    hi, i got your code working but i need a little help.. i want to display the user ip address too.. is there anything ?

  19. Moosa says:

    Hi Adam,

    i am a bigginer for website creating, desperatedly seaching for a help and unable to find. my need is that how can i create a Div, like a comment box in a webpage to show base on their country, lets say i have a webpage name, Maldives and if some one visit from Maldives they can see the comment box but if some one visit from outside maldives they can view the page but not able to see the comment box.

    • Adam McFarland says:

      Hi Moosa,

      I think in that instance I’d do what you’re describing server-side, although it can be accomplished with javascript. One new resource that I’ve found for IP geolocation that works really good is http://freegeoip.net/

      If you were to get their location using that service in say PHP, you could parse it with json_decode. An example would be:

      json_decode(file_get_contents('http://freegeoip.net/json/' . $ip), true);

      Where $ip is the user’s IP.

      You can then use an if statement to show the form (i.e. if the user is from Maldives, show the form, else don’t show it).

      Hope that bit of pseudo code helps!

      Adam

  20. Pratik Nayak says:

    Hi Adam,
    Thank for this api,
    Please find working demo of above code with source to get better idea for others.
    http://jsfiddle.net/006c5mfj/1/

    is there any way to get ip address also.

    Rgds,

    Pratik

    • Adam McFarland says:

      Thanks Pratik! Getting the IP address in javascript is more work than on a server side language like php. There’s a good thread on this on StackOverflow

  21. Brian says:

    Did anyone experience problems with “google.loader.ClientLocation”?

    It worked fine September 28 and September 29 it doesn’t work anymore.

    Pratik Nayak’s example (http://jsfiddle.net/006c5mfj/1/) from above also doesn’t work since you get the error: “google.loader.ClientLocation is null”.

    Your Geo Location JavaScript is simple & great and shows almost every time the right country.

    • Adam McFarland says:

      Hi Brian,

      That’s unfortunate. We’re not using it in production so I don’t keep an eye on it. It’s possible that Google got rid of this functionality. I did some quick searching and couldn’t find any info. Does anyone else have any insight?

      – Adam

  22. sudhir says:

    Hello Adam

    where is api key .. i cannot find it. so what i can do this .

    please suggest me

    thanks
    sudhir

    • Adam McFarland says:

      Hi Sudhir,

      It appears as though this is no longer working as Brian pointed out a few weeks ago. I’ll make a note on the post.

      – Adam

  23. Glen says:

    The demo seems to work fine. Any changes? I’m not being able to make this work but that is probably because I’m new to JS and trying to display on a visualforce page

    • Adam McFarland says:

      Hi Glen,

      It’s odd that the demo works for you, it’s not working for me. I doubt anything has changed on Google’s end. I’m working on a follow-up post about geolocation using PHP that does currently work. Keep an eye out for that over the next few weeks.

      – Adam

  24. Ron Woolley (private please) says:

    As this is now late 2016, Google has dropped it’s IP# lookup services all together. Some may still work, not sure, but are generally noted redundant and all will soon cease.

    MUCH BETTER
    Google now supports AJAX (Jason!) style autocomplete APIs that work absolutely magically. All a visitor has to enter is perhaps a city/region and maybe street or a state/country to reduce lists of like names, and very quickly for most around the world a drop list of choices appears. Based on their extensive mapping nohow and hugmongus DBs the info is amazing.

    Their selection from the lists can then be auto inserted in your waiting corresponding form fields (form object IDs clearly described). One can even add ones own street number and street name and receive ALL the info you need embedded; even map co-ordinates in hidden fields if you want.

    That’s not to say you need ALL the info available or that visitors want to give it to you anyway (except perhaps for shipping blah), but try the examples; its quite amazing for a free service suitable for most sites.

    ======================================
    What is / was wrong with IP# lookup.

    Its unfortunate that so many posters on many forums and comment lists I visit do not understand the concepts behind “IP#” geo-locationing in its various forms but then why should they, most aren’t interested in pursuing years of programming experience.

    But what is mostly unfortunate are all the incorrect posts between the posters which go uncorrected and clarified by others. Hopefully this will help some website owners and business people. I do not intend to tell people what they must do, only inform.

    Just because an occasional IP# lookup here or there reports a position of country state and even suburb which is very close to ones own does NOT in any way define one service as necessarily better than another. IP# locating is all about discovering where ones registered ISP SERVER used is located and as most use many servers that can be mean…
    * even if your ISP contract gives you a STATIC IP# that IP# may be reported on the net as coming from any one of the ISPs load shared servers AND that can result sometimes as suggesting you are located tens, hundreds, even a thousand or so KMs away.
    *NON static IP#s usually are the most confusing (especially when using the likes of WIFI and un-wired services via the mobile networks) as resources are continuously exited to the web across the phone networks least loaded servers.

    Therefore information posted to you beyond the visitors “Country” of origin is regularly inaccurate.

    If your site is monitised or your needs for accurate locality acquisition is otherwise of prime importance, require your visitors to fill in that data manually.

    GSM (Global System for Mobile communication) available in modern smart phones is the only way AUTOMATIC reliably accurate locality acquisition is possible (if it is switched on!). But just for those visitors using their smart phones one needs more sophisticated code both client and server side (website) to handle that info.

    My suggestion for what it’s worth is at least use a server side service like “ip2location.com” or “maxmind.com” to obtain AND LIST the visitors COUNTRY and use that as an enticement through your displayed perceived professionalism to expect the rest of the details will be properly filled in. It becomes a joke when visitors are being told graphically that they are located in a city far away even interstate.

    PS while “ip2lcation.com” offer the best prices for highly accurate “ISPs” IP# location data. “maxmind.com” do offer the largest sets of “free” data file records but they (the DBs) are considerably lacking. See both sites caveats.

    Both sites offer download software scripts of various flavors so one can AUTO download their monthly updates and locally serve the DB data requests for your processes. It is also not difficult to perform decompression of any DB formats that are downloaded in compressed format at each monthly download.

    And be aware that some of the smaller ip# lookup services actually use the maxmind free db and leave a lot to be desired re keeping current.

    Regards, Ron W (Au)

Leave a Reply

Your email address will not be published. Required fields are marked *

Commenting Rules

I'm honored that you found this post interesting enough to leave a comment. Before posting, I have a few ground rules:

  • Please keep your comments as relevant to the post as possible.
  • No personal attacks or any other nastiness.
  • Your first comment is subject to my approval.

Thanks!