【发布时间】:2017-11-08 23:17:24
【问题描述】:
我正在尝试从我的旧程序方法转向 javascript 编码,转向更基于对象的方法。我尝试迁移的代码之一是我的位置跟踪器,如下所示:
var gps = new geolocation();
function geolocation() {
this.watchID;
this.position;
this.success = function(p) {
this.position = p;
};
this.failure = function(error) {
var errmsg;
// convert the error code to a readable message
switch(error.code)
{
case error.PERMISSION_DENIED:
errmsg="App doesn't have permission to access your location.";
break;
case error.POSITION_UNAVAILABLE:
errmsg="Your location information is unavailable to App.";
break;
case error.TIMEOUT:
errmsg="App's request to get your location timed out.";
break;
case error.UNKNOWN_ERROR:
errmsg="An unknown GPS error occurred.";
break;
}
console.log(errmsg);
};
this.watchPosition = function() {
if(!this.watchID)
{
this.watchID = navigator.geolocation.watchPosition(this.success, this.failure, { maximumAge: 1000, timeout: 15000, enableHighAccuracy: true });
}
};
this.getPosition = function() {
return(this.position);
};
this.clearWatch = function() {
if(this.watchID)
{
// turn off the watch
navigator.geolocation.clearWatch(this.watchID);
this.watchID = null;
console.log("GPS WatchID was cleared.", "GPS Status");
}
};
};
我可以访问此对象中的所有方法。当我开始 gps.watchPosition(); this.watchID 被设置。但是,当我使用时:
var p = gps.getPosition();
我得到 p 为“未定义”并且通过调试器运行显示 this.position 也是未定义的。
如果我将此代码恢复为程序状态,它可以正常工作。显然,我遗漏了一些东西,但我就是不知道是什么。
(注意:我在发布之前对这段代码做了一些最小化)
【问题讨论】:
-
-
watchPosition 在初始化时被调用...我可以等待一整分钟然后点击 getPosition 并获得相同的结果。就像我说的,我可以把它移回程序上,它工作得很好。
标签: javascript object methods w3c-geolocation