Why is my function returning undefined?


Here is the link to my project can you figure out why my getLoc() function is returning undefined.

Not familiar with json, but did you look at your console? 1 error and 2 warnings showing up.

OK, breaking it apart so I can add an error function, I get:

function getLoc() {
  function locSuccess(pos) {
    console.log("success!");
    console.log(pos);
    var lat = pos.coords.latitude;
    var lon = pos.coords.longitude;
    return [lat,lon];
  }
  
  function locError(err) {
    console.log("error!");
    console.log(err);
  }
  navigator.geolocation.getCurrentPosition(locSuccess, locError);
}
console.log(getLoc());

When I check the console, I see that there is indeed an error - “Only secure origins are allowed (see: https://goo.gl/Y0ZkNV).”

Now, I’m remembering that that will only accept calls from a secure “https” web site and not an insecure one like codepen that is “http” (for now).

That is why I used a different way to get lat and lon:

  $.getJSON("http://ip-api.com/json", function (data) {
    lat = data.lat;
    lon = data.lon;
/* continue with your code */
2 Likes

An alternate solution to what @ksjazzguitar suggested would be to use https for Codepen link as Codepen supports both protocols. But better solution is the one suggested by him.

hey can you please send the whole javascript code please I am stuck.

Well, that can be a good start. Start with this:

$.getJSON("http://ip-api.com/json", function (data) {
  var lat = data.lat;
  var lon = data.lon;

  console.log("Your lat = " + lat + " and lon = " + lon);
  
  /* continue with your code */
  
});

Be aware that the getJSON is asynchronous so it has to be handled specially. The program isn’t going to wait for it to finish before it moves on. One way to handle that is to put the code that needs lat and lon inside the callback function as I’ve done in the above example. The callback isn’t run until getJSON isn’t finished so it works fine.

If you make the mistake of putting it outside, like:

var lat;
var lon;

$.getJSON("http://ip-api.com/json", function (data) {
  lat = data.lat;
  lon = data.lon;  
});

console.log("Your lat = " + lat + " and lon = " + lon);

THIS IS BAD! getJSON is run asynchronously so the program gets to console.log before lat and lon before they are defined.