1

I need to have longitude and latitude inside the input form, but I cannot figure out how to do it, I have tried a few examples, as seen in the below code (doesnt work).

<script>
function data(){

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

function getLocation() {
  if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
  }
}

function showPosition(position) {
  x.innerHTML = 
  "Latitude: " + position.coords.latitude + 
   "<br>Longitude: " + position.coords.longitude;
}
}</script>

<form name="test_form">
  <input id="demo" type="text" value=""> 
</form>
<button onclick="getLocation();">GO</button>

Expected results: Longitude and Latitude to be inside the input box, or if possible, longitude in one input box, latitude in anoter

1
  • Welcome to StackOverflow! This is a good question! well done... Commented May 1, 2019 at 17:42

3 Answers 3

2

You need to set the value of the input instead of overriding its HTML.

like

// set the value of the input x.value = "Latitude: " + position.coords.latitude + ...

Updated to include separate boxes for Lat/Lon

See demo below

function showPosition(position) {
  console.log('location obtained');
  console.log(position);

  var lon = document.getElementById("lon");
  var lat = document.getElementById("lat");

  // set the value of the inputs
  lon.value = position.coords.longitude;
  lat.value = position.coords.latitude;
}

function getLocation() {
  console.log('button clicked');

  if (navigator.geolocation) {
    console.log('getting location');
    navigator.geolocation.getCurrentPosition(showPosition);
  }
}
label {
  width: 100px;
  font-weight: bolder;
  display: inline-block;
}
<label>Longitud:</label><input id="lon" type="text" value=""> <br/>
<label>Latitude:</label><input id="lat" type="text" value=""> <br/>
<button onclick="getLocation();">GO</button>

Sign up to request clarification or add additional context in comments.

Comments

1

Here you go:

Markup

<input id="lat" type="text" value=""> 
<input id="long" type="text" value=""> 
<button onclick="getLocation();">GO</button>

JS

function getLocation(){
      navigator.geolocation.getCurrentPosition(function(position){
        var coordinates = position.coords;
        document.getElementById('lat').value = coordinates.latitude;
        document.getElementById('long').value = coordinates.longitude;
      });
   }

Comments

1

You have to set the x.value = instead of its innerHTML.

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.