Skip to content
Advertisement

how can I get the geolocation in html using JavaScript

I am looking for a way to get the geolocation and then convert the latitude and longitude to the closet city.

<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>

This is what iv got to get the latitude and longitude but am not sure how to find the closet city using them.

Advertisement

Answer

You should use an API for geolocation, I suggest ipdata for example. It’s easy to use, just put this function in your code:

function json(url) {
  return fetch(url).then(res => res.json());
}

let apiKey = 'your_api_key';
json(`https://api.ipdata.co?api-key=${apiKey}`).then(data => {
  console.log(data.ip);
  console.log(data.city);
  console.log(data.country_code);
  // so many more properties
});

PS: replace ${apiKey} with your ipdata API key, you will find it in your dashboard after you create an account in ipdata.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement