0

I'm trying to call the only object in a array but this always returns undefined. if i log the whole array i can see everything in it, if i call the object of it it returns undefined!

The code:

var pos = [];

this code is inside a function____

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) { 
        pos.latlng = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };  
        console.log(position.coords.latitude);

    });
}

 console.log(pos.latlng);  <--- undefined
 console.log(pos);         <--- works fine
 console.log(pos[0].latlng); <--- also tried this

Result of console.log(pos);

Object
latlng : Object
   lat : 52.136624499999996
   lng : 5.3469106
   __proto__:Object
__proto__:Object
5
  • Old question about attempting to access a value set inside an Asynchrouns function outside it! Commented Mar 13, 2017 at 13:53
  • Plus pos is an array not an object. The way you're using it it should be declared like: var pos = {}. Commented Mar 13, 2017 at 13:56
  • I've also tried this! also returns undefined. Commented Mar 13, 2017 at 13:58
  • plese add the result of console.log(pos); <--- works fine. Commented Mar 13, 2017 at 13:59
  • Edited the post, its in there Commented Mar 13, 2017 at 14:03

6 Answers 6

2

I suggest to push the new object to pos.

pos.push({
    lat: position.coords.latitude,
    lng: position.coords.longitude
});

Access then

pos[0].lat
Sign up to request clarification or add additional context in comments.

4 Comments

Forgot to mention! but i have also tried this, this returns: Cannot read property 'lat' of undefined
Why cannot create key value pair like pos.latlng = { lat: position.coords.latitude, lng: position.coords.longitude }; ?
You should mention that all code depending of an asynchronous function should be used exclusively inside that function or after that function is done!
it is inside of the initmap() function if that helps anything
0

actually an array is an object except its properties are numbers between 0 an 2³² - 2 and the length property, so yes you can do :

 var pos = [];
    pos.inneObject= {//object
      prop: 'property'
    };

pos.innerObject will exist. But if you try to console.log(pos) you will get '[]' but if you do

for (properties in pos){
console.log(pos[properties])// you will get pos.innerObject
}

Therefore your issue is something else! here you log the property before they have been created, move you console.log in the callback of navigator.geolocation.getCurrentPosition like this:

var pos = [];

this code is inside a function____

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) { 
        pos.latlng = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };  
        console.log(position.coords.latitude);

 console.log(pos.latlng);  <--- undefined
 console.log(pos);         <--- works fine
 console.log(pos[0].latlng); <--- also tried this

    });
}

that should work;

6 Comments

Yeah! they do work inside of this callback indeed, how can i make it so i can call it somewhere else aswell? I'm guessing some sort of delay or call it later?
you can trigger an event at the end of the callback and listen to the callback to perform subsequent actions
Hmm because later in the function i call another function with this object as parameter. This is after i created a marker for the maps, then i call both the marker and pos object to a function to calc the distance.
yes I see, but the thing is that getCurrentPosition is async function, and the callback inside is what is executed as soon as getCurrentPosition returns. in your example, your console.log are outside the callback so the are executed before getCurrentPosition returns. So every function that is supposed to use the position data should wait for that function to return. You can't really assess the time it will take, so you have 2 solutions: Call the subsequents functions in the callback. Or trigger an event in the callback that says "we received position data".. do you see what I mean?
Ah yes i see, so the console.log triggers before the getcurrentposition. because everything continues while getcurrentposition is still running? Would it be possible to continu with the rest, after the getcurrentposition is done? Thanks so much for the help btw,
|
0

The issue here is that getCurrentPosition is async. The function you give as an argument, also known as the callback, will not be called until it is done getting the current position.

I do not know what you are using here to get the current position, but you need to make sure that you do not use the result until the callback has been invoked.

Comments

0

This is because you first defined pos as an array, then you treated it as an anonymous object. Either take it as an array or anonymous object.

If you want to have latlan property, then define pos as following at the beginning of the code:

pos = {};

Otherwise, you can't have a property for an array. So you need to remove it and take the 0 index as lon and the 1st index as latitude:

pos = [];
pos.push(position.coords.longitude); // pos[0];
pos.push(position.coords.latitude); // pos[1];

Comments

0

based on what @ibrahim-mahrir said .

you can a promise to reslove your position:

var pos = {};

this code is inside a function____

    getPos(){

      return new Promise(function(resolve){
        if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) { 
             resolve({
              lat: position.coords.latitude,
              lng: position.coords.longitude
            });  
        });
      });
    }

getPos().then(function(pos){

  console.log(pos.lat);
  console.log(pos.lng);
})

Comments

0

pos should be an object (but this is not where the error comes from).

The error is probably caused because of the asynchronity of the function getCurrentPosition. If it does it work asynchronously then the logging will happen before the value get assigned to pos. You should either do the logging inside the callback of getCurrentPosition, or wrapp the logging inside a function and call it from inside the callback.

var pos = {}; // object

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) { 
        pos.latlng = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };


        // SOLUTION ONE: use pos here
        console.log(pos);
        console.log(pos.lating);

        // SOLUTION TWO: call a function that do the logging
        logPos();
    });
}

function logPos() {  // will be called after the value is assigned
    console.log(pos);
    console.log(pos.lating);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.