Iam a total JS Newb, and trying to structure my simple JS code a bit. Goal is to get users location.
It works, but the getUserCoordinates function does not return an value? I think it is just a logical failure from a beginner?
var app = {
geocoder: null,
init: function() {
this.geocoder = new google.maps.Geocoder();
coordinates = this.getUserCoordinates();
console.log(coordinates); // empty??
return;
},
getUserCoordinates: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (coords) {
console.log(coords); // works Geocoder Object!
return coords; // the problem
}, // more code
No, it’s a quite common error for beginners. The
getCurrentPositionmethod is asynchronous (it takes some time to determine the location) and does return nothing. When finished, it will invoke thecallbackfunction you passed into it – somewhen in the future. The value is only available inside that callback, or to functions that are called from there.