【问题标题】:Grabbing longitude and Latitude value from a function从函数中获取经度和纬度值
【发布时间】:2013-09-18 22:14:05
【问题描述】:

请问我如何在它们的函数之外获取“lat”和“lon”的值,以便在页面上的其他位置使用。

   navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);  

    function handle_errors(error)  
    {  
        switch(error.code)  
        {  
            case error.PERMISSION_DENIED: alert("user did not share geolocation data");  
            break;  
            case error.POSITION_UNAVAILABLE: alert("could not detect current position");  
            break;  
            case error.TIMEOUT: alert("retrieving position timed out");  
            break;  
            default: alert("unknown error");  
            break;  
        }  
    }  
   function handle_geolocation_query(position){  
        var lat = (position.coords.latitude);
       var lon = (position.coords.longitude); 

    }

我要做的是获取设备的经度和纬度并将其作为参数传递给查询和数据库,也将相同的值用于其他事物。我不知道该怎么做。 任何帮助将不胜感激。

【问题讨论】:

  • 这将有助于标记语言!
  • 谢谢@Steve,已经完成了

标签: javascript jquery map geolocation


【解决方案1】:

我想到的第一件事(在这么晚的时间:D)是这样的:

  • 在处理程序之外声明一个变量,比如说:

    var coords = {};

  • 然后在你的“handle_geolocation_query”处理程序中,触发一个事件,让你知道你的位置已经准备好了,假设你正在使用 jQuery:

    $(coords).trigger('positionReady', position);

  • 之后,在您需要这些坐标的任何地方,监听您的自定义“positionReady”事件,然后完成您的工作:

    $(coords).on('positionReady', function(e, position) { 控制台.log(位置); });

这将帮助您避免“意大利面条式代码”,但同时,您需要异步“思考”,并且可能以您需要的(正确)方式使用回调。

【讨论】:

  • 谢谢你,我去试试,我会更新你的结果
  • 你好@Nicolae 我试过你的建议,但是当我提醒它时它返回未定义
  • 它返回 undefined 因为它在 handle_geolocation_query 之前执行的警报会给你一个值。
猜你喜欢
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 2019-08-04
  • 1970-01-01
  • 2019-03-25
  • 2016-09-29
相关资源
最近更新 更多