Geolocation in HTML5

-3

I have the following code:

<!DOCTYPE html>
<html>
<body>

<p>Presiona el botón para obtener tus coordenadas.</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 = "Geolocalización no es soportada por tu navegador.";
    }
}

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


</body>
</html>

How do I remove the button and have it automatically put the latitude and longitude in a text field?

    
asked by Pedro Jimenez 30.06.2017 в 03:52
source

1 answer

1

Your function is correct, if I understood correctly what you want is that it works when the page loads and not when the button is touched, right?

This you can achieve in several ways, one that I would use, is to expect all the contents of the sun to be loaded and then call the function.

Something like that using your code:

var x = null; 

document.addEventListener("DOMContentLoaded", function(event) {
    x = document.getElementById("demo");
    getLocation();
  });

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocalización no es soportada por tu navegador.";
    }

}

function showPosition(position) {
        if(x != null)
    {
        x.innerHTML = "Latitud: " + position.coords.latitude + 
      "<br>Longitud: " + position.coords.longitude;
    }
}

And in reality that's all, try it, replace what you have within <script></script> for that and when you load your page the coordinates will appear alone.

    
answered by 30.06.2017 / 13:09
source