我有以下代码:
$scope.gotoBottom = function() {
$timeout(function() {
$location.hash('footer');
$anchorScroll();
}, 100);
};
我需要能够访问函数外部的Loc变量或通过GetLocation函数。因为我需要将它绑定到我正在创建的网格中,以便为非现场员工存储和关闭工作信息。
以下是使用变量Loc
的代码function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert('Geolocation is not supported by this browser');
}
}
function showPosition(position) {
alert(position.coords.latitude + ' ' + position.coords.longitude);
var Loc = position.coords.latitude + ' ' + position.coords.longitude;
}
非常感谢任何帮助
答案 0 :(得分:0)
可以通过两种方式实现
在函数
之外声明Locvar Loc = '';
function showPosition(position) {
alert(position.coords.latitude + ' ' + position.coords.longitude);
Loc = position.coords.latitude + ' ' + position.coords.longitude;
}
或者,只需删除Loc中的'var'即可。它现在被声明为全局(http://www.w3schools.com/js/js_scope.asp)
function showPosition(position) {
alert(position.coords.latitude + ' ' + position.coords.longitude);
Loc = position.coords.latitude + ' ' + position.coords.longitude;
}
答案 1 :(得分:0)
navigator.geolocation.getCurrentPosition()正在异步模式下运行,函数showPosition(position)是用于捕获位置的回调函数。因此,您需要将所有与位置相关的代码放在此回调函数中。例如,你可以这样做:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(whenWeGetPosition);
}
else {
alert('Geolocation is not supported by this browser');
}
}
function whenWeGetPosition(position) {
// your code to use position
var rowId=timesheetGrid.uid();
var pos = timesheetGrid.getRowsNum();
timesheetGrid.addRow(rowId,["","","","<?php echo $ActiveWeek; ?>","","","","","","","","","","",Loc],0); //adds a new row with pre filled data
timesheetGrid.selectCell(rowId,0,false,true,true); // Focus on the new row
}
getLocation();
答案 2 :(得分:0)
var Loc = position.coords.latitude + ' ' + position.coords.longitude;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert('Geolocation is not supported by this browser');
}
}
function showPosition(position) {
alert(position.coords.latitude + ' ' + position.coords.longitude);
}
Make it global by moving it outside the function.