Eqbal
Eqbal

Reputation: 1879

Can't Save coordinates vars from Google Map [object HTMLInputElement]

<script>
var lat ;
if(true) {
        navigator.geolocation.getCurrentPosition(GetLocation);
        function GetLocation(location) {
            var lat = location.coords.latitude;
        }           
};  

alert(lat);
 </script>  

Now I get [object HTMLInputElement] , am I doing anything wrong here ?

Upvotes: 1

Views: 1040

Answers (1)

Neil
Neil

Reputation: 8111

The problem is, you are declaring a variable with the same name in your function, this means you have two variables, a global one and a local one. So when you alert the global variable it hasn't been set to anything.

All you need to do is remove the var keyword from your function:

// global or other scope

var lat, firstUpdate = false;

if(true) {
    navigator.geolocation.getCurrentPosition(GetLocation);
    function GetLocation(location) {

        // don't use var here, that will make a local variable
        lat = location.coords.latitude;

        // this will run only on the first time we get a location.
        if(firstUpdate == false){
           doSomething();
           firstUpdate = true;
        }

    }           
};  

function doSomething(){
    alert(lat);
}

Edit:

I have edited the answer to show how you can make sure you call a function once you have found your first fix.

Upvotes: 2

Related Questions