Get user geo-information without API in JS

Get user geo-information without API in JS

You heard it right, you don't need to pay APIs just to get user geo-location information. I got your back like I always did. ๐Ÿ‘Œ

ยท

2 min read

While working on my project, iSendMoney, I encountered a challenge: obtaining the active user's geo-location without relying on APIs. Determined to find a solution, I embarked on a journey of reverse-engineering an API that once provided this information effortlessly. Surprisingly, the process turned out to be much simpler than anticipated. Although the resulting response is limited, it proved to be adequate for my needs at the time. I invite you to dive in, explore, and feel free to tweak and enhance this approach. Your valuable feedback is greatly appreciated!

Allow me to present the JSON format used by the API provider to list countries in an array. Behold, the comprehensive JSON list: https://gist.github.com/13x54n/fc29e0553c2967cbff2068ceb27e4181

[
  {
    "name": "Nepal",
    "code": "NP",
    "emoji": "๐Ÿ‡ณ๐Ÿ‡ต",
    "unicode": "U+1F1F3 U+1F1F5",
    "image": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NP.svg"
  },
  ...
]

With the assistance of ChatGPT, I successfully obtained an updated object containing countries and their respective time zones, formatted as follows:

var countries = {
    AD: "Andorra",
    AE: "United Arab Emirates",
    ...
}

var timezones = {
    "Africa/Abidjan": {
      u: 0,
      c: ["CI", "BF", "GH", "GM", "GN", "ML", "MR", "SH", "SL", "SN", "TG"],
    },...
}

That was all I needed to get the current user location with the flag icon, country name, and code. But again with the help of ChatGPT, you can add a key to the response object say currency code or anything as per need.

export function getCountry() {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

  if (timezone === "" || !timezone) {
    return null;
  }

  const _country = timezones[timezone].c[0];
  const country = countries[_country];
  return country;
}

export function getState() {
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

  if (timezone === "" || !timezone) {
    return null;
  }

  const state = timezone.split("/")[1].replace("_", " ");

  return state;
}

The possibilities for utilizing this function are endless. For instance, I employed it in the iSendMoney project to retrieve the currency code, the active user's geolocation, and the nearest location to the user. Happy hacking! Although this blog may not be as concise as my usual writing style, I have strived to maintain consistency for the sake of clarity.

Did you find this article valuable?

Support Sangya Sherpa by becoming a sponsor. Any amount is appreciated!

ย