Skip to content

Instantly share code, notes, and snippets.

@marcosfreitas
Created November 21, 2013 17:47
Show Gist options
  • Save marcosfreitas/7586213 to your computer and use it in GitHub Desktop.
Save marcosfreitas/7586213 to your computer and use it in GitHub Desktop.
Script to implements MaxMind GeoIp Free JavaScript Service
<!--
Please, remember to append this html on footer:
<span id="mm_credits">
This website uses <a href="http://www.maxmind.com/en/javascript">GeoIP2 JavaScript from MaxMind</a>.
</span>
-->
<script src="//j.maxmind.com/js/apis/geoip2/v2.0/geoip2.js" type="text/javascript"></script>
<script>
/*
Hey! I've disabled the redirection for you see the console info generated before enable this functionality.
I'm sorry for my bad english :c
*/
var redirect = (function () {
/* This implements the actual redirection. */
var redirectBrowser = function (site) {
// I've changed this function because the default have not a folder '/br' but have '/en'
if(site === 'br'){
var uri = "http://www.yoursite.com.br/";
}else{
var uri = "http://www.yoursite.com.br/"+site;
}
window.location = uri;
};
/* These are the country codes for the countries we have sites for.
* We will check to see if a visitor is coming from one of these countries.
* If they are, we redirect them to the country-specific site. If not, we
* redirect them to world.example.com */
var sites = {
"en": true,
"br": true
};
var defaultSite = "br";
var onSuccess = function (geoipResponse) {
/* There's no guarantee that a successful response object
* has any particular property, so we need to code defensively. */
if (!geoipResponse.country.iso_code) {
//redirectBrowser("br");
console.warn("Oh no! What is your iso code? We'll redirect you to default Brasilian site.");
return;
}
/* ISO country codes are in upper case. */
var code = geoipResponse.country.iso_code.toLowerCase();
console.info(":) We've found this iso_code to your Country: ",code);
if ( sites[code] ) {
//redirectBrowser(code);
console.info("We'll redirect you to similar site in your language: ",sites[code]);
}
else {
// redirectBrowser("");
console.warn("We understand what is happened... but We'll redirect you to default Brasilian site.");
}
};
/* We don't really care what the error is, we'll send them
* to the default site. */
var onError = function (error) {
// redirectBrowser("br");
console.warn("We've found an error. :( We'll redirect you to default Brasilian site. { "+error+" }" );
};
return function () {
geoip2.country( onSuccess, onError );
};
}());
redirect();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment