JavaScript地理位置错误 - 回调函数错误

时间:2015-06-26 21:57:05

标签: javascript html5 cordova w3c-geolocation

我正在使用从设备读取gps坐标的HTML / JavaScript应用程序。我遇到的问题是我收到以下错误:

Uncaught TypeError: Failed to execute 'getCurrentPosition' on 'Geolocation': The callback provided as parameter 1 is not a function.

这是JavaScript:

var app = {

  position: null,

  // Application Constructor
  initialize: function() {
    alert("app.initialize invoked");
    console.log("Initializing google map");
    $(document).ready(this.onDeviceReady); 
  },


  // Execute on success - when calling this function invoke with this. prefixed
  onSuccess: function() 
  {
    alert("app.onSuccess invoked");
    var lat = geolocation.coords.latitude;
    var lng = geolocation.coords.longitude;
    localStorage.setItem("Latitude", lat);
    localStorage.setItem("Longitude", lng);
    alert("lat: " + lat + "long: " + lng);
  },

  // Execute on failure - when calling this function invoke with this. prefixed
  onError: function() 
  {
    alert("Code: " + error.message);
  },


  // Execute on deviceReady - when calling this function invoke with this. prefixed
  onDeviceReady: function() 
  {
    alert("app.onDeviceReady invoked");
    var options = { enableHighAccuracy: true };
    alert("app.onDeviceReady invoked +2");

    //<------------------- vv Does not work vvv -------------------
    navigator.geolocation.watchPosition(this.onSuccess, this.onError, options);
    alert("app.onDeviceReady invoked +3");

  },



  // Attach google map to div
  showGoogleMap: function() 
  {

  } 

};

function onLoad() {
  alert("onLoad invoked");
  app.initialize();
}

所以它不喜欢我注册回调函数的方式 - this.onSuccess。我该怎么解决这个问题?有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

我的问题的答案是在调用onSuccess和onError函数时不要使用 this 。正确的调用是:

  position = navigator.geolocation.getCurrentPosition(app.onSuccess, app.onError, options);

Kerry Shotts指出了这一点:

https://groups.google.com/forum/#!topic/phonegap/TIjA3TPpQt0