【问题标题】:Get data from geolocation in javascript从javascript中的地理位置获取数据
【发布时间】:2012-09-27 17:55:48
【问题描述】:

我正在编写地理定位脚本,但无法获取函数的内容。

有人可以帮助我吗?

代码如下:

<script type="text/javascript">
var myvalue1;
navigator.geolocation.getCurrentPosition(function()
{
    myvalue1 = 'test';
    window.myvalue2 = 'demo';
});

console.log(myvalue1);
console.log(window.myvalue2);
</script>

两者都返回未定义,我根本不知道如何提取数据。

希望有人可以帮助我。

提前致谢。

【问题讨论】:

  • 它是一个异步调用。 console.log(myvalue1); 这一行在myvalue1='test' 之前被调用,只有当用户允许共享权限时才会调用。因为,myvalue1 最初是 undefined,它反映了相同的

标签: javascript function variables global


【解决方案1】:

是异步调用。试试这个

<script type="text/javascript">
var myvalue1;
navigator.geolocation.getCurrentPosition(function()
{
    myvalue1 = 'test';
    window.myvalue2 = 'demo';
    console.log(myvalue1);
    console.log(window.myvalue2);
});


</script>

【讨论】:

    【解决方案2】:

    我认为您的 getCurrentPosition 没有被调用。将其放在文档就绪事件中。

    【讨论】:

      【解决方案3】:

      试试这个:

      <script type="text/javascript">
      
      var coords;
      
      function outputPosition()
      {
          console.log('(' + coords.latitude + ', ' + coords.longitude + ')');
      }
      
      navigator.geolocation.getCurrentPosition(function(position)
      {
          coords = position.coords;
          outputPosition();
      });
      
      /*
          coords will still be undefined here because the callback function
          for getCurrentPosition has not been called yet.
      */
      
      </script>
      

      【讨论】:

      • 是的,我知道。问题是我真的需要函数之外的信息。
      • 我更新了我的代码。 coords 在异步调用回调之前不会被分配。您可以通过调用另一个函数来访问函数外部的信息。
      • 是的,我可以用这种方法制作一个很好的解决方案。谢谢:D
      猜你喜欢
      • 2013-11-17
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多