javascriptw3c-geolocation

Assign the latitude and longitude from Geolocation's getCurrentPosition to variables


I am trying to use the values of longitude and latitude that are returned by getCurrentPosition() api as shown in the example on W3Schools below:

<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>
The example above just displays those values on the web page. However, I would like to save them in a local javascript variable (say y and z) so I can use them elsewhere. For example, if my longitude (y) is 10 and latitude (z) is 15, then I would be able to display them as follows:

y=10
z=15

Solution

  • You mean like this?

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Coords will load momentarily.</p>
    
    
    
    <p id="demo"></p>
    
    <script>
    var x = document.getElementById("demo");
    
    var lat = '';
    var lon = '';
    
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    
    function showPosition(position) {
        lat = position.coords.latitude;
        lon = position.coords.longitude;
        x.innerHTML = lat + " " + lon;
    
    
    }
    
    getLocation();
    </script>
    
    </body>
    </html>
    

    You don't have to declare the values at the global level like I did, but thought it might be useful so you can access it outside of the function.