【发布时间】:2012-08-28 12:33:08
【问题描述】:
FindMyLocation 定义如下:
function FindMyLocation(callback) {
if (navigator.geolocation) {
var locationMarker = null;
if (locationMarker) {
return;
}
navigator.geolocation.getCurrentPosition(
function(position){
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
addMarker(
position.coords.latitude,
position.coords.longitude,
"You are here"
);
setTimeout(function(window) {
callback.call(pos);
}, 1000);
},
function (geoPositionError) {
switch (geoPositionError.code) {
case 0:
alert('An unknown error occurred, sorry');
break;
case 1:
alert('Permission to use Geolocation was denied');
break;
case 2:
alert('Couldn\'t find you...');
break;
case 3:
alert('The Geolocation request took too long and timed out');
break;
default:
}
},
timeoutCallback, 10, {maximumAge:60000, timeout:50000, enableHighAccuracy:true}
);
var positionTimer = navigator.geolocation.watchPosition(
function( position ){
updateMarker(
locationMarker,
position.coords.latitude,
position.coords.longitude,
"Updated / Accurate Position"
);
}
);
setTimeout(
function(){
// Clear the position watcher.
navigator.geolocation.clearWatch( positionTimer );
},
(1000 * 60 * 5)
);
} else {
alert("Your phone browser doesn't support geolocation.");
}
}
function timeoutCallback(){
alert('Hi there! we are trying to locate you but you have not answered the security question yet.\n\nPlease choose "Share My Location" to enable us to find you.');
}
我的主页中运行了这段代码:
FindMyLocation(function() {
myPos = this;
});
当我在回调中 console.log myPos 时,我看到了值。但是,我希望能够在此回调之外使用 myPos 来进行距离计算。现在不行。
请帮忙。
【问题讨论】:
-
@David:当我尝试提醒或 console.log myPos(被声明为全局)时,我得到了未定义。有任何想法吗?就此而言,我不擅长回调和 JavaScript。
-
"
However, I want to be able to use myPos outside this callback in order to do a distance calculation." 为什么不在回调内部进行距离计算呢?或者,如果您定期进行距离计算,或响应事件,只需在进行计算之前测试是否已定义myPos(如果尚未设置,则显示“仍在获取位置...”之类的消息)。 -
@apsillers:我做到了。非常感谢。异步编程需要一段时间才能掌握。
标签: javascript geolocation w3c-geolocation