我正在编写一个程序,一个记录用户位置的Web服务。该程序使用地理定位来查找用户,并在检索到该位置后继续记录该位置。由于地理定位使用回调函数来获取位置,因此程序在具有该位置之前无法继续。问题是我不能在地理定位功能中继续该程序,因为需要其他变量。所以我所做的是geoolcaion函数使用以下函数显示网页上的位置
function geoFindMe(){
navigator.geolocation.getCurrentPosition(success, error, geo_options);
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var altitude = position.coords.altitude;
var accuracy = position.coords.accuracy;
var time = getTime();
//post the everything somewhere and then the callback function will fetch the info
//may use var time = position.timestamp;
$("#result").append(time + " " + latitude + " " + longitude);
}
function error(error) {
alert("Unable to retrieve your location due to "+error.code + " : " + error.message);
}//there was a semicolon here
var geo_options = {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
};
}
此函数由以下代码
调用 geoFindMe(function successful(){
//first call geoFindMe function then call successful as a callback
//the function will retrieve the information that was displayed by the geoFindMe on the webpage
$("#result").hide();
var currentLocation = document.getElementById('result');
document.getElementById('result').innerHTML = "";
var moved = hasMoved(previousLocation, currentLocation);
var time = isItTime(moved, lastBuffer, 15);
if(time){//its time to put the location in the buffer
currentLocation = currentLocation + "#";// this way we will be able to differentiate between different locations
charBuffer.wrap(currentLocation);
}
dump(stringArray, lastDump, true);
});
我想要做的是一旦找到地理定位然后调用成功的函数,我试图做一个回调函数。问题是,由于某种原因,它正在跳过大部分成功的回调函数,并继续行转储(...);有什么建议?也许我没有正确地写出成功的功能?非常感谢
答案 0 :(得分:0)
您所要做的就是在geoFindMe函数中添加一个参数来接受回调。然后在成功函数中调用它
function geoFindMe(callback){
navigator.geolocation.getCurrentPosition(success, error, geo_options);
function success(position) {
callback&&callback(); // Check if callback exists and then call it.
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var altitude = position.coords.altitude;
var accuracy = position.coords.accuracy;
var time = getTime();
//post the everything somewhere and then the callback function will fetch the info
//may use var time = position.timestamp;
$("#result").append(time + " " + latitude + " " + longitude);
}
function error(error) {
alert("Unable to retrieve your location due to "+error.code + " : " + error.message);
}//there was a semicolon here
var geo_options = {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
};
}