问题描述
请问我如何在它们的函数之外获取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.
这篇关于从函数中获取经度和纬度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!