无法保存来自Google地图的坐标变量[object HTMLInputElement] [英] Can't Save coordinates vars from Google Map [object HTMLInputElement]
本文介绍了无法保存来自Google地图的坐标变量[object HTMLInputElement]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<脚本>
var lat;
if(true){
navigator.geolocation.getCurrentPosition(GetLocation);
函数GetLocation(location){
var lat = location.coords.latitude;
}
};
alert(lat);
< / script>
现在我得到[object HTMLInputElement],我在这里做了什么错误?
解决方案
问题是,您在函数中声明了一个具有相同名称的变量,这意味着您有两个变量,全局变量和局部变量。所以当你提醒全局变量时,它没有被设置为任何东西。
所有你需要做的就是从你的函数中删除var关键字:
//全局或其他作用域
var lat,firstUpdate = false;
if(true){
navigator.geolocation.getCurrentPosition(GetLocation);
函数GetLocation(location){
//不要在这里使用var,这会使局部变量
lat = location.coords.latitude;
//这将只在我们第一次获得位置时运行。
if(firstUpdate == false){
doSomething();
firstUpdate = true;
}
}
};
函数doSomething(){
alert(lat);
}
编辑: $ b
我编辑了答案,以显示如何确保在找到第一个修复程序后调用函数。
<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 ?
解决方案
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.
这篇关于无法保存来自Google地图的坐标变量[object HTMLInputElement]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文