简体   繁体   English

javascript中的全局变量获取Geolocation

[英]global variable in javascript to get Geolocation

i am using the following code to access the geolocation of the blackberry device. 我使用以下代码访问黑莓设备的地理位置。 its working and showing the desire result. 它的工作和展示欲望的结果。 but i want to access the window.GlobalVar outside the body of this function. 但我想访问此函数体外的window.GlobalVar。 how can i access it? 我怎么才能访问它? please help. 请帮忙。

 navigator.geolocation.getCurrentPosition(function(position) {  
  var gps = (position.coords.latitude+position.coords.longitude);  
  window.GlobalVar = gps;
  alert (window.GlobalVar);
});

Best regards, 最好的祝福,

window.GlobalVar will be accessible outside of your function. window.GlobalVar可以在你的函数之外访问。

What's probably going wrong here is that you're trying to access it before it has been set, seeing as it is being set in a callback function. 这里可能出现的问题是你在设置它之前试图访问它,因为它正在回调函数中设置。

getCurrentPosition prompts the user for coordinates, but it is not a blocking call, ie it does not simply halt all code execution and wait for the user to make a decision. getCurrentPosition提示用户输入坐标,但它不是阻塞调用,即它不会简单地停止所有代码执行并等待用户做出决定。

This means that you do not set window.GlobalVar during page load, you request it during page load, and you set it whenever the user decides to . 这意味着您不会在页面加载期间设置window.GlobalVar ,您在页面加载期间请求它,并且您可以在用户决定时设置它。 So no matter where you call getCurrentPosition you cannot be sure that at a given point, window.GlobalVar will be set. 所以无论你在哪里调用getCurrentPosition你都无法确定在给定的点上是否会设置window.GlobalVar

If you want to be sure that window.GlobalVar is set in the script you're running, you need to make sure that you're running the script after the variable has been set. 如果要确保在正在运行的脚本中设置window.GlobalVar则需要确保在设置变量运行脚本。

navigator.geolocation.getCurrentPosition(function(position) {  
  var gps = (position.coords.latitude+position.coords.longitude);  
  window.GlobalVar = gps;

  continueSomeProcess();
});

function continueSomeProcess() {
   // this code will be able to access window.GlobalVar
}

Calling window.gps after setting window.gps = gps should be enough as it has a global scope since you attached it to window . 在设置window.gps = gps之后调用window.gps应该足够了,因为它具有全局范围,因为您将它附加到window Take care of the fact that JS is asynchronous, ie gps might not be defined when you call it. 注意JS是异步的这一事实,即在调用它时可能没有定义gps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM