Location Based Custom Content Geolocation with JavaScript

In this guide, I will demonstrate how to show different content based on the country, city or timezone of a website visitor, called content geolocation.

All with easy JavaScript and step-by-step instructions!

Content Geolocation

This method uses ShinyGeoip, a free Geolocation API that relies on the “Maxmind GeoLite2 Database” to fetch location data of IP addresses. Your options are to either use the ready hosted API or run it on your own server.

I’ve already written a guide for doing this on WordPress with PHP — this is the JavaScript version that you can use on websites written in HTML.

Content Geolocation with JavaScript;

Step 1. Setup your own Geolocation API if you don’t want to rely on the third-party server, which is however designated for production use (instructions here).

Step 2. Add this piece of JavaScript code to your HTML file;

<script>
function geolocationSwitch(data) {
if (data.country.code === 'UK') {
document.write('<p>You are a site visitor from the UK</p>');
} else {
document.write('<p>You are not located in the UK</p>');
}
}
</script>

<script src="https://geoip.nekudo.com/api/?callback=geolocationSwitch""></script>

Change the country code “UK” to any other two-letter country code, such as US (United States), CA (Canada), AU (Australia), CN (China), etc.

For more complicated HTML elements, for example JavaScript inside the script. Start the script tag with “\x3Cscript>” and end it with “\x3C/script>”.

Also apostrophe “‘” should be preceded by a backslash “\”.

You can also change the “data.country.code” part to “data.city” to match cities, or “data.location.time_zone” to match timezones. However, this data is not available for all visitors or IP addresses. Country information is most reliable.

If you are hosting your own Geolocation API, simply change the ready hosted “geoip.nekudo.com” URL to your own subdomain.

It’s that simple to show custom content on your HTML based website, depending on the geographical location of the visitor. Hope this helped!

Thanks for having a read and visiting my blog. Tim.

Twitter Button Facebook Button Google Button LinkedIn Button

Leave a Reply

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