Example Description
In this example, we detect where site visitors are accessing our site from, and based on our findings we redirect the visitor to a page containing content that is customized for that location.
How We Built It
In this example we used the wix-window API in order to get the geographic coordinates of the site visitor, and then identified the actual country name of that location using a third-party API service called LocationIQ.
In order to use this example, register for an API key on their site to allow you to use their services.
Secrets Manager
We added the API key that was provided by LocationIQ to the Secrets Manager, which is located in the Settings section of your site's dashboard.
Router
We added a Router that is responsible for routing our site visitors according to their location to the corresponding dynamic page.
Home Page Code
On our Home page we added a text element, to display a greeting for the site visitor. When the visitor accesses the site, the following happens:
We use getCurrentGeolocation() from the wix-window API to get the site visitor's coordinates. This will only succeed if the site visitor's Geolocation service is enabled.
We call the backend function getCountryFromLocation() from location.jsw in order to get the country name, based on the site visitor's location determined in the previous step.
We use the wix-location API to redirect the visitor to a location-based dynamic page.
Router Page Code
On our router page we added a text element to display the name of the country the site visitor is accessing our site from.
When the site visitor reaches the Router page (‘geo-page’), this means that the geo_Router() function (in routers.js) responded with ok(), indicating that it contains the country name in its RouterData. We use the wix-window API to extract this information, and assign it to our text element.
Backend Code
location.jsw
The function getCountryFromLocation() first gets the LocationIQ API key from the Secrets Manager. Then, it uses fetch from wix-fetch API in order to request information regarding the coordinates it received as arguments. Finally, the function returns the country name that matches the found location.
routers.js
The geo_Router() function is triggered when the site visitor is redirected from the main page. If the request parameter doesn’t contain a name of a country, the function returns a notFound() response. Otherwise, it returns an ok() response to the router page (‘geo-page’) and passes the name of the country along with the response.
Related Examples
Did this help?
|
Thanks for your feedback!
City Weather
Get weather information according to city
Intermediate
Currency Converter
Convert a specified amount of money from one currency to another
Intermediate
Secrets Manager
Store API keys in a secure manner using Secrets Manager.
Intermediate