JavaScript Geolocation Error - callback function error

7.3k views Asked by At

I am working HTML/JavaScript app that reads gps coordinates from the device. The issue I am having is that I get the following error:

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

Here is the 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();
}

So it doesn't like the way I am registering the callback function - this.onSuccess. How should I fix this? Any ideas?

Thanks

1

There are 1 answers

0
Ubaidul Khan On BEST ANSWER

The answer to my question is to NOT use this when calling the onSuccess and onError function. The correct invocation is:

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

This was pointed out by Kerry Shotts:

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