使用位置从W3C地理返回
问题描述:
FindMyLocation定义如下:使用位置从W3C地理返回
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来进行距离计算。现在,它不会工作。
请帮忙。
答
<script lang="JavaScript" type="text/javascript">
$.post(window.baseUrl + 'includes/tagmap.php',
{ name:"<?php echo $value->business_name; ?>",
x: "<?php echo $value->x; ?>",
y: "<?php echo $value->y; ?>",
action:"populate"}, function(data){
var locdata = $.parseJSON(data);
function ShowMyLocation() {
FindMyLocation(function(myPos) {
myPos = this; addMarker(locdata.x,locdata.y,locdata.name);
})
FindMyLocation();
}
ShowMyLocation();
});
</script>
什么问题? – David
@David:当我尝试提醒或console.log myPos(声明为全局)时,我得到未定义的值。有任何想法吗?对于这个问题,我在回调和JavaScript方面不够强大。 “ – Mina
”'但是,我希望能够在此回调之外使用myPos来进行距离计算。“为什么不在回调中计算距离?或者,如果您定期执行距离计算或响应某个事件,只需在计算之前测试是否定义了“myPos”(并且如果还没有设置,则显示一条消息,如“仍在获取位置...” )。 – apsillers