I'm searching for a straight forward, simple solution to set a default currency for my users (clientside/web), based on their location. No external API shall be called.
Apparently, this procedure requires two steps:
- determine location
- map location to a currency (i.e. 'USD', 'GBP', 'EUR')
So far, I tried using navigator.language
(see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) to receive the language, and then mapped the language to a currency, i.e. de -> EUR, en -> GBP
However, navigator.language
does not seem like the correct tool, as it is not precise enough. It may returns 'de' for swiss for example, which has a different currency to EUR.
Any guidance and idea is welcome.
Thanks in advance.
CodePudding user response:
There's a few options but they all have drawbacks:
- You can ask for the location of the user using the Geolocation API, but using this API requires permission from the user (e.g. annoying popup). This is overkill if all you want to do is set some default currency setting, but if you have other stronger use cases for knowing the user's location then this may be an option for you.
- You can guestimate the location by analyzing the
navigator.language
as you are trying to do and then use that to translate it to a currency. But there will be many situations where this approach will select the wrong currency. E.g. Spanish speakers who live in the USA; any user who doesn't live in an English speaking country but prefers to have their computer language set to English. - If you have access to the server, you can use the IP-address of the user to get an approximate location. Depending on your use case you may not actually need a IP-to-Geo API, but an offline database like this one may suffice: https://github.com/datasets/geoip2-ipv4 There are also commercial parties that can provide you bigger and more up to date databases but it'll come at a cost. IP-to-Geo is probably the most common approach when websites want to do something with the location of the user, without explicitly asking permission.
- Similar to the approach using
navigator.language
, on the server you can analyze the incomingAccept-Language
header.