JavaScript   

Get location data from ipapi’s geolocation API using JavaScript

This short JavaScript code snippet can be used to read location data from IPAPI’s geolocation API.  It uses JavaScript ajax call to fetch the API URL and prints the JSON response of the API. This code snippet can be customized to get results from other API URLs also.

  var apiURL = 'https://ipapi.co/json';
  function getLocation(url){
    var response;
    var x = new XMLHttpRequest();
    x.open("GET", url, true);
    x.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        response = JSON.parse(this.responseText);
        //console.log(response);
        console.log(response.city);
        console.log(response.country);
        console.log(response.country_calling_code);
        console.log(response.country_capital);
        console.log(response.country_code);
        console.log(response.country_code_iso3);
        console.log(response.country_name);
        console.log(response.country_population);
        console.log(response.country_tld);
        console.log(response.currency);
        console.log(response.currency_name);
        console.log(response.ip);
        console.log(response.languages);
        console.log(response.latitude);
        console.log(response.longitude);
        console.log(response.postal);
        console.log(response.region);
        console.log(response.region_code);
        console.log(response.timezone);
      }
    }
    x.send();
  }
  getLocation(apiURL);
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us