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

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

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.

Leave a Comment