Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Created February 25, 2020 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/d532d79f5f496a5ee3b44485b8977eb8 to your computer and use it in GitHub Desktop.
Save erkobridee/d532d79f5f496a5ee3b44485b8977eb8 to your computer and use it in GitHub Desktop.
detect user location
/*
version updated to use the fetch API
source:
https://github.com/AdeyinkaAdegbenro/Detect_Location/blob/master/detect_location.js
*/
function request(url) {
return fetch(url).then(response => response.json());
}
function ipLookUp () {
request('http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
getAddress(response.lat, response.lon)
},
function fail(data, status) {
console.log('Request failed. Returned status of', status);
}
);
}
function getAddress (latitude, longitude) {
request(
'https://maps.googleapis.com/maps/api/geocode/json?' +
'latlng=' + latitude + ',' + longitude + '&key=' +
GOOGLE_MAP_KEY
)
.then(
function success (response) {
console.log('User\'s Address Data is ', response)
},
function fail (status) {
console.log('Request failed. Returned status of',status)
}
)
}
if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log(
'latitude', position.coords.latitude,
'longitude', position.coords.longitude
)
getAddress(
position.coords.latitude,
position.coords.longitude
)
},
function error(error_message) {
// for when getting location results in an error
console.error(
'An error has occured while retrieving' +
'location', error_message
)
ipLookUp()
}
);
} else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment