Advertisement
Coding-Developer

Detect a users location geolocation API

Dec 11th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. function ipLookUp () {
  2. $.ajax('http://ip-api.com/json')
  3. .then(
  4. function success(response) {
  5. console.log('User\'s Location Data is ', response);
  6. console.log('User\'s Country', response.country);
  7. getAddress(response.lat, response.lon)
  8. },
  9.  
  10. function fail(data, status) {
  11. console.log('Request failed. Returned status of',
  12. status);
  13. }
  14. );
  15. }
  16.  
  17. function getAddress (latitude, longitude) {
  18. $.ajax('https://maps.googleapis.com/maps/api/geocode/json?' +
  19. 'latlng=' + latitude + ',' + longitude + '&key=' +
  20. GOOGLE_MAP_KEY)
  21. .then(
  22. function success (response) {
  23. console.log('User\'s Address Data is ', response)
  24. },
  25. function fail (status) {
  26. console.log('Request failed. Returned status of',
  27. status)
  28. }
  29. )
  30. }
  31.  
  32. if ("geolocation" in navigator) {
  33. // check if geolocation is supported/enabled on current browser
  34. navigator.geolocation.getCurrentPosition(
  35. function success(position) {
  36. // for when getting location is a success
  37. console.log('latitude', position.coords.latitude,
  38. 'longitude', position.coords.longitude);
  39. getAddress(position.coords.latitude,
  40. position.coords.longitude)
  41. },
  42. function error(error_message) {
  43. // for when getting location results in an error
  44. console.error('An error has occured while retrieving' +
  45. 'location', error_message)
  46. ipLookUp()
  47. });
  48. } else {
  49. // geolocation is not supported
  50. // get your location some other way
  51. console.log('geolocation is not enabled on this browser')
  52. ipLookUp()
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement