get user location javascript – How to get a user’s location with JavaScript?

get user location javascript : Detect location and local timezone of users in JavaScript. Q – How to get user location using Javascript / HTML5 Geolocation?

Gelocation API
To get the user’s current location, i required to use the getCurrentPosition() method of the js geolocation object.

if (window.navigator.geolocation) {
 // Geolocation available
} 

How to get a user’s location with JavaScript?

get user location javascript using the getCurrentPosition function.

window.navigator.geolocation
  .getCurrentPosition(console.log, console.log);

Get current position

getCurrentPosition(successCallback, failureCallback);

Output

{
  coords = { 
    latitude: 49.4554803,
    longitude: -2.0843058,
    altitude: null,
    accuracy: 44,
    altitudeAccuracy: null,
    heading: null,
    speed: null,
  },
  timestamp: 1583860898576
}

Geocoding

const successfulLookup = position => {
  const { latitude, longitude } = position.coords;
  fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=youraddedkeyhere`)
    .then(response => response.json();
    .then(console.log); // Or do whatever you want with the result

Also Read : Get current location latitude and longitude jQuery

Also Read This ๐Ÿ‘‰   add/remove multiple input fields dynamically with javascript

getCurrentPosition function.

window.navigator.geolocation
  .getCurrentPosition(successfulLookup, console.log);

Gives something like ’48, My street(Like ganesh sco), My Town(Rajkot), My Post Code(360002), My Country(India). Get user’s current location using HTML5 Geolocation API in JavaScript Example.

results[0].formatted; 

Find Your User’s Location in JavaScript Using an API Example

Get User Location with Javascript

index.html

<div id="IP">
</div>
<div id="Country">
</div>
<div id="loc">
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

function getData () {
 $.ajax({
        url: 'https://ipinfo.io',
        dataType: 'jsonp',       
        jsonp: 'callback',
    })
  .then(
      function success(results) {
         $("#IP").html(results.ip);
          $("#Country").html(results.country);
           $("#loc").html(results.loc);
         console.log(results.ip, results.country,results.loc);

      },

      function fail(data, status) {
          console.log('Request failed.  Returned status of',
                      status);
      }
  );
}
getData()
</script>

I hope you get an idea about get user location javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donโ€™t forget to share.