How to take values from an array without array.push

Asked

Viewed 59 times

0

Guys, I’m trying to get a user’s location and it keeps updating from time to time, searching, I found this method, however, I can not only do this with the current value of the array, it concatenates (push) and adds infinitely.. someone knows how I can solve this?

 var array = [];
   navigator.geolocation.watchPosition(function(position) {
   var lat = position.coords.latitude;
   var lon = position.coords.longitude;
   var vel = position.coords.speed;
   array.push(lat, lon, vel); 
   locationCode()  
});

function locationCode() {
   console.log(array)
   alert(array[0]);
}
  • And if you put var array = []; at the beginning of the function?

  • What do you mean? I don’t understand

  • You can create an object and update it instead of an array, in my opinion it is even clearer

  • That line var array = []; is out of function function(position) {, right? If you put in, right at the beginning?

  • So every time the function is called, the array will be restarted from scratch.

  • I’ll try, I’ll put her right at the beginning, thanks for the idea, I’ll test.

  • unfortunately did not, array is not defined

  • Keep the array out and within zero it var array = []; navigator.geo... { array = []

  • Right. Then leave it as it was, and within the function puts only array = [];, without the var

  • Dude, you guys are geniuses, it worked!

  • There @Guilhermecostamilam, put the answer there.

  • Guys, now another problem has arisen as always in informatica, how can I get the value of the array out of the function? I need it to mark the user’s real-time location on the map

Show 7 more comments

1 answer

1


Only one explanation:

var array = []; //Cira o array
navigator.geolocation.watchPosition(function(position) {
   array = []; //Zera o array

   //Cria variáveis com os valores
   var lat = position.coords.latitude;
   var lon = position.coords.longitude;
   var vel = position.coords.speed;

   //Adiciona os valores ao array
   array.push(lat, lon, vel);

   //Chama uma função que mostra os dados
   locationCode()  
});

function locationCode() {
   console.log(array)
   alert(array[0]);
}

You can do a little bit more lean:

let array = [];

navigator.geolocation.watchPosition(function(position) {
    array = [position.coords.latitude, position.coords.longitude, position.coords.speed];

    alert(array);
    console.log(array);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.