Home > Mobile >  how can I get the geolocation in html using JavaScript
how can I get the geolocation in html using JavaScript

Time:08-30

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.

CodePudding user response:

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.

  • Related