【发布时间】:2014-07-14 21:56:55
【问题描述】:
我正在尝试编写一个从 JavaScript 收集用户位置的应用程序。我目前正在使用 Geolocation API 从笔记本电脑上进行调试,并且证明它可以在给定的时间内工作。它每隔几秒钟广播一次我的位置,然后在我移动 5-10 秒后重新计算。事实证明,出于某种原因,这会占用我的大量电池/CPU。如果我要在手机上使用这个应用程序,它会通过 GPS 广播我的位置还是通过本地蜂窝塔对它的位置进行三角测量?
var latitude, longitude, accuracy, angle;
function setGeolocation(prevID) {
var geoID = window.navigator.geolocation.watchPosition(getPosition,handleErrors,{maximumAge: 1000, enableHighAccuracy: true});
//Pass the ID's to the seeMyGeoID function.
seeMyGeoID(geoID,prevID);
function getPosition(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
accuracy = position.coords.accuracy;
angle = position.coords.heading;
console.log(latitude+" "+longitude+" "+accuracy+" "+angle);
};
function handleErrors(err){
if (err.code == 1){
console.log("PERMISSION_DENIED");
}
if (err.code == 2){
console.log("POSITION_UNAVAILABLE");
}
if (err.code == 3){
console.log("TIMEOUT");
}
};
};
function seeMyGeoID(geolocationID,previousID){
if(geolocationID != previousID){
previousID = geolocationID;
//Wait 1 second.
setTimeout(function(){
navigator.geolocation.clearWatch(previousID);
navigator.geolocation.clearWatch(previousID+1);
setGeolocation(previousID);
},1000);
}
};
//Call function for the first time.
setGeolocation(0);
//I want this code to be able to take a position every 0.5-1 second, or in real time (but that may be pushing it).
【问题讨论】:
标签: javascript html gps geolocation location