Skip to content

Instantly share code, notes, and snippets.

@ihorduchenko
Last active March 17, 2022 15:51
Show Gist options
  • Save ihorduchenko/9d0e1625a5ea06d394b448ee8f1a62ef to your computer and use it in GitHub Desktop.
Save ihorduchenko/9d0e1625a5ea06d394b448ee8f1a62ef to your computer and use it in GitHub Desktop.
Detect user's location using Geolocation API and LocationIQ API
const langText = document.querySelectorAll('.langText');
const gbText = document.querySelectorAll('.gbText');
const euText = document.querySelectorAll('.euText');
function handleLocation() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
var lat = crd.latitude.toString();
var lng = crd.longitude.toString();
var coordinates = [lat, lng];
getLocation(coordinates);
return;
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
}
function getLocation(coordinates) {
var xhr = new XMLHttpRequest();
var lat = coordinates[0];
var lng = coordinates[1];
// Paste your LocationIQ token below.
xhr.open('GET', "https://us1.locationiq.com/v1/reverse.php?key=pk.8b7b3045c07074dae90b2a165cd693f3&lat=" +
lat + "&lon=" + lng + "&format=json", true);
xhr.send();
xhr.onreadystatechange = processRequest;
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var resp = JSON.parse(xhr.responseText);
console.log(resp);
if (resp.address.country_code == 'gb') {
gbText.forEach(function(el) {
el.classList.remove('hide');
});
} else {
euText.forEach(function(el) {
el.classList.remove('hide');
});
}
return;
}
}
}
handleLocation();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment