user7886229
user7886229

Reputation: 927

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

Upvotes: 0

Views: 1282

Answers (2)

ENEMUSE
ENEMUSE

Reputation: 1

<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 = "y= " + position.coords.latitude + 
    "<br>z= " + position.coords.longitude; 
}
</script>

Upvotes: 0

espradley
espradley

Reputation: 2148

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.

Upvotes: 1

Related Questions