Javascript 从函数中获取经度和纬度值
请告诉我如何获得“lat”和“lon”在其函数之外的值,以便在页面上的其他位置使用Javascript 从函数中获取经度和纬度值,javascript,jquery,map,geolocation,Javascript,Jquery,Map,Geolocation,请告诉我如何获得“lat”和“lon”在其函数之外的值,以便在页面上的其他位置使用 navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors); function handle_errors(error) { switch(error.code) { case error.PERMISSION_D
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);
}
我试图做的是获取设备的经度和纬度,并将其作为参数传递给查询和数据库,同时在其他事情中使用相同的值。我想不出该怎么办。
任何帮助都将不胜感激。我首先想到的是(在这么晚的时候:D)是这样的:
- 在处理程序外部声明一个变量,例如: var-coords={}
- 然后在“handle\u geolocation\u query”处理程序中,触发一个事件,该事件为您提供一个位置就绪的idea,假设您正在使用jQuery: $(coords).trigger('positionReady',position)
- 然后,在需要这些坐标的任何地方,监听自定义的“positionReady”事件,并完成您的工作: $(coords).on('positionReady',函数(e,位置){ 控制台日志(位置); });
这将帮助您避免“意大利面代码”,但同时,您需要异步地“思考”,并可能以您需要的(正确的)方式使用回调。标记语言会有帮助!谢谢@Steve,已经这么做了谢谢,我要试试,我会更新你的结果你好@Nicolae我试过你的建议,但当我发出警报时它返回未定义,因为它在处理地理位置查询之前执行的警报会给你一个值。