1

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.

TJ8678
  • 91
  • 7
  • https://stackoverflow.com/questions/6548504/how-can-i-get-city-name-from-a-latitude-and-longitude-point – Sergey Sosunov Aug 25 '22 at 23:23
  • Does this answer your question? [How can I get city name from a latitude and longitude point?](https://stackoverflow.com/questions/6548504/how-can-i-get-city-name-from-a-latitude-and-longitude-point) – Konrad Aug 25 '22 at 23:26

1 Answers1

0

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.

Omar Lamin
  • 62
  • 1
  • 8