Im trying to get the current position of the user into an object variable but it keeps resetting on it self.
var UserCoords = { lat: '', lng: '' };
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
UserCoords.lat = position.coords.latitude;
UserCoords.lng = position.coords.longitude;
console.log(UserCoords);//Works
}
function getUserCoords() {
getLocation();
console.log(UserCoords);//Returns lat and lng empty
OtherFunction(UserCoords.lat, UserCoords.lng);
}
I also tried:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
UserCoords.lat = position.coords.latitude;
UserCoords.lng = position.coords.longitude;
console.log(UserCoords);//Works
});
}
But neither works.
I want to do this because i need to use the users position in some other functions and i would like to not have to call geolocation every time.
UPDATE:
jsfiddle: http://jsfiddle.net/9fvcqcvz