Skip to content

Geolocation

Drew Baker edited this page Apr 25, 2021 · 2 revisions

How to enable and use the built in Geo Location features.

First thing to note is, that almost always you want to organize a site around "regions" not countries. And these regions are generally programmer-defined, so this plugin is built to allow the programmer to define what "regions" the site needs, and then place users from specific countries in those regions.

1. Set IP Stack API key

In the .env file, set the IP Stack API key. It is saved in 1Password.

2. Enable the plugin

In nuxt.config.js under plugins un-comment ip-geolocate.js.

3. Install nuxt-vuex-localstorage NPM package

You will most likely want nuxt-vuex-localsto, to remember a users location between page visits. You simply need to install it, nothing else needed.

4. Define "regions" that you want

Often you'll want to group countries into regions, and use those regions to build out sections of the site. You can replace "regions" with "offices", it's all the same.

In the ~/store/geolocation.js file, you'll find a getter function called region. This is where you'd define what countries belong to what region.

5. Access a users location

The plugin will automatically fetch the users location on page load. It will save the users location to the store under this.$store.state.geolocation. But you can access the users "region" by using the getter like so: this.$store.getters["geolocation/region"]

Almost always, you'd prefer to have the users "region" that any specific location data about them from the store.

TIP: The location is only available client side, so be sure to use the page route when building out pages, and redirect to the correct route based on the users region

6. Update the users location manually

Often times you'd want to allow the user to update their saved region. You can do this by using the following store commit:

this.$store.commit(geolocation/SET_GEOLOCATION, "Users new region")

The idea is that a user will generally click a button to change their region, not provide the country they are in.