0

Is there something as simple as plug in the code and go for geolocation? I only want countries so that my website can switch to the appropriate language.

It seems that the ones I found are either deprecated, have less than 10 users, are paid/trial versions.

kod
  • 13
  • 3

1 Answers1

0

Faced this problem recently - indeed there are only paid options out there. However, there is an almost free solution is to use Google Cloud functions for that.

https://cloud.google.com/functions/docs/create-deploy-gcloud

Here is the code of a function you want to implement:

const cors = require('cors')

const corsOptions = {
  origin: true
}

function _geolocation(req, res) {
  const data = {
    country: req.headers["x-appengine-country"],
    region: req.headers["x-appengine-region"],
    city: req.headers["x-appengine-city"],
    cityLatLong: req.headers["x-appengine-citylatlong"],
    userIP: req.headers["x-appengine-user-ip"],
  }

  res.json(data)
};

exports.geolocation = (req, res) => {
  const corsHandler = cors(corsOptions);

  return corsHandler(req, res, function() {
    return _geolocation(req, res);
  });
};

Then in the JS code of your web-page you call this function and get country from data.country.

However, if what you want is the language selection - I recommend using auto-selection of the language included in Django. Add to your middlewares:

MIDDLEWARE = [
    ...
    'django.middleware.locale.LocaleMiddleware',
]

It will autodetect user's language based on browser settings. More info: https://docs.djangoproject.com/en/4.1/topics/i18n/translation

Egor Wexler
  • 1,754
  • 6
  • 22