从函数中获取经度和纬度值

Grabbing longitude and Latitude value from a function(从函数中获取经度和纬度值)
本文介绍了从函数中获取经度和纬度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please how do i get the value of "lat" and "lon" outside their function to use else where on the page.

   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); 

    }

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

What i am trying to do is to get the longitude and latitude of a device and pass it is as a parameter to query and database, also use that same value for other things. I cant figure out how to go about it. Any help will be much appreciated.

推荐答案

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

The first thing came my mind (at this late hour :D) is something like this:

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

  • declare a variable outside your handlers, let's say:

var coords = {};

var coords = {};

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

then in your 'handle_geolocation_query' handler, trigger an event that gives you an ideea that your position is ready, assuming you're using jQuery:

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

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

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

after that, everywhere you need those coordinates, listen for your custom 'positionReady' event, and do your job:

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

$(coords).on('positionReady', function(e, position) { console.log(position); });

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

This will help you to avoid 'spaghetti code', but in the same time, you need to 'think' asynchronously, and maybe using callbacks the (right) way you need.

这篇关于从函数中获取经度和纬度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)