2

I've got a function on my webpage that gets the user's geolocation. How do I automatically load the latitude and longitude into an input box when the page loads without using the OnClick function?

function showlocation() {
   // One-shot position request.
   navigator.geolocation.getCurrentPosition(callback);
}

function callback(position) {
   document.getElementById('latitude').innerHTML = position.coords.latitude;
   document.getElementById('longitude').innerHTML = position.coords.longitude;
}
Ihsaan
  • 33
  • 4

2 Answers2

1
function showlocation() {
  navigator.geolocation.getCurrentPosition(callback);
}

function callback(position) {
  document.getElementById('latitude').value = position.coords.latitude;
  document.getElementById('longitude').value = position.coords.longitude;
}

window.onload = function () {
  showlocation();
}

  <input type="text" id="latitude">
  <input type="text" id="longitude">
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

This line of code listens for when all your HTML is loaded and calls showLocation as soon as the DOM is ready to be manipulated.

window.addEventListener('DOMContentLoaded', showLocation);

The answer you accepted does work, but DOMContentLoaded is typically much faster, which gives you a more responsive UI.

Supporting proof: Difference between DOMContentLoaded and Load events

Community
  • 1
  • 1
akamaozu
  • 695
  • 1
  • 7
  • 15