0

I'd like to determine what country a visitor of my website is from based off of their geoIP so I can determine whether that visitor is visiting their country-specific website or not and prompt them with a confirmation popup asking if they'd like to be redirected in the event that they're not. However, my JavaScript knowledge is limited/minimal. How would I store/use and return a specific value to be used dynamically from a JSON response?

For example, I'd like to use the following country iso code "US".

"country": {
    "iso_code": "US",

Using MaxMind's GeoIP2 JavaScript Client API with the following JavaScript:

<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>

<script type="text/javascript">

var onSuccess = function(location){
  console.log(
  "Lookup successful:\n\n"
  + JSON.stringify(location, undefined, 4)
  );
};

var onError = function(error){
  console.log(
      "Error:\n\n"
      + JSON.stringify(error, undefined, 4)
  );
};

geoip2.city(onSuccess, onError);

</script>

This JSON returned looks like this:

{
  "city": {
    "geoname_id": 5368361,
    "names": {
      "es": "Los Ángeles",
      "fr": "Los Angeles",
      "ja": "ロサンゼルス",
      "pt-BR": "Los Angeles",
      "ru": "Лос-Анджелес",
      "zh-CN": "洛杉矶",
      "de": "Los Angeles",
      "en": "Los Angeles"
    }
  },
  "continent": {
    "code": "NA",
    "geoname_id": 6255149,
    "names": {
      "fr": "Amérique du Nord",
      "ja": "北アメリカ",
      "pt-BR": "América do Norte",
      "ru": "Северная Америка",
      "zh-CN": "北美洲",
      "de": "Nordamerika",
      "en": "North America",
      "es": "Norteamérica"
    }
  },
  "country": {
    "iso_code": "US",
    "geoname_id": 6252001,
    "names": {
      "ru": "США",
      "zh-CN": "美国",
      "de": "USA",
      "en": "United States",
      "es": "Estados Unidos",
      "fr": "États-Unis",
      "ja": "アメリカ合衆国",
      "pt-BR": "Estados Unidos"
    }
  },
  "location": {
    "accuracy_radius": 50,
    "latitude": 34.0669,
    "longitude": -118.3109,
    "metro_code": 803,
    "time_zone": "America/Los_Angeles"
  },
  "postal": {
    "code": "90020"
  },
  "registered_country": {
    "iso_code": "US",
    "geoname_id": 6252001,
    "names": {
      "ja": "アメリカ合衆国",
      "pt-BR": "Estados Unidos",
      "ru": "США",
      "zh-CN": "美国",
      "de": "USA",
      "en": "United States",
      "es": "Estados Unidos",
      "fr": "États-Unis"
    }
  },
  "subdivisions": [
    {
      "iso_code": "CA",
      "geoname_id": 5332921,
      "names": {
        "zh-CN": "加利福尼亚州",
        "de": "Kalifornien",
        "en": "California",
        "es": "California",
        "fr": "Californie",
        "ja": "カリフォルニア州",
        "pt-BR": "Califórnia",
        "ru": "Калифорния"
      }
    }
  ],
  "traits": {
    "autonomous_system_number": 7018,
    "autonomous_system_organization": "AT&T Services, Inc.",
    "isp": "AT&T Services",
    "organization": "AT&T Internet Services",
    "ip_address": "12.125.142.34"
  },
  "represented_country": {
    "names": {}
  }
}

GeoIP2 JavaScript Tutorial

Thanks in advance.

Chad
  • 13
  • 1

2 Answers2

0

You already have a Json, then you could do something like this:

var onSuccess = function(location){
  console.log(location.country.iso_code);
};
Emeeus
  • 5,072
  • 2
  • 25
  • 37
  • How can I use/store the returned value of `location.country.iso_code` to populate HTML dynamically or use it elsewhere? – Chad Jul 30 '18 at 23:35
  • @Chad It depends on what do you want to do with this value. See this http://jsfiddle.net/q710h6ns/2/ – Emeeus Jul 30 '18 at 23:43
0

In addiction to Emeeus answer, if you want to save locally the response in order to not repeat the request to server or ask user twice the same question, you may use window.localStorage object. This object will persist data in the user browser even when user closes the browser, and data will be available for your domain. If you want to store just while user is browsing your site in that moment, and clear on close, use sessionStorage.

You should always pass a string to a field of localStorage. Your code would be something like:

var geoData;
var onSuccess = function(location){
  window.localStorage.geoData = JSON.stringify(location);
  // ... do whatever you want with location ...
};

// ... on error ...

if (! window.localStorage.geoData)
  geoip2.city(onSuccess, onError);
else
  onSuccess(JSON.parse(window.localStorage.geoData));

Remember that JSON.parse can throw an error if the JSON is not valid. I recommend you to surround the code with a try {...} catch (e) {geoip2.city(onSuccess, onError)}, as if the parse fails, it the catch will be executed and can request the server for data normally.

E. Zacarias
  • 598
  • 6
  • 19