Last active
March 17, 2022 15:51
-
-
Save ihorduchenko/9d0e1625a5ea06d394b448ee8f1a62ef to your computer and use it in GitHub Desktop.
Detect user's location using Geolocation API and LocationIQ API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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