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

陌路散爱 提交于 2019-12-08 03:56:32

问题


<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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/11475192/cant-save-coordinates-vars-from-google-map-object-htmlinputelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!