get location in javascript

To get the current location of a user in JavaScript, we can make use of the Geolocation API provided by modern web browsers. Here's a simple example:

index.tsx
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showPosition);
} else {
  console.log("Geolocation is not supported by this browser.");
}

function showPosition(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  
  console.log("Latitude: " + latitude);
  console.log("Longitude: " + longitude);
}
372 chars
14 lines

Here, we first check if the navigator.geolocation object is available in the user's browser. If it is, we call the getCurrentPosition method to retrieve the user's current position. This method takes a callback function showPosition as its parameter, which is called with a Position object that contains the latitude and longitude coordinates of the user's location.

Inside the showPosition function, we extract the latitude and longitude values from the Position object and log them to the console. From here, you can use this data in any way you like to customize your pages based on the user's location.

gistlibby LogSnag