Place the value of a javascript variable in a textarea

0

Good day I would like to deposit the result that a variable of javascript throws at me in a textarea, thanks in advance!

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "La geolocalizaci&oacuten no es soportada por este navegador.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
} 
    
asked by django 23.11.2017 в 17:45
source

2 answers

0

Your code should work. You just have to call the function getLocation .

Keep in mind that the browser will request permission from the user to obtain the location and you should take into account the possibility that the user does not consent.

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, noPosition);
  } else {
    x.innerHTML = "La geolocalizaci&oacuten no es soportada por este navegador.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
    "\nLongitude: " + position.coords.longitude;
} 

function noPosition(positionError){
  console.log(positionError);
}

getLocation();
#demo{
  width: 250px;
  height: 80px;
}
<textarea id="demo" ></textarea>
    
answered by 23.11.2017 в 17:57
0

Your code I see it well as such, all you have to do is run / call the function that captures the geolocation getLocation();

NOTE: A line break within a text content is done with \n and not with <br>

I leave the functional code:

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "La geolocalizaci&oacuten no es soportada por este navegador.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + '\n' +
    "Longitude: " + position.coords.longitude;
} 

getLocation();
<textarea id="demo" cols="50"></textarea>
    
answered by 23.11.2017 в 17:57