0

I have two text boxes that I want users to fill with geolocation data (latitude and longitude). I want to have a button, so when users click it, the text boxes are filled instantly with the geolocation data.

Thanks to w3schools, I can replace the text in two paragraph tags to the locations, but I'd like the button fill up the text boxes. Here's what I have now. Anyone have an answer?

<!DOCTYPE html>
<html>
<body>

<form>
Latitude: <input type="text" name="Latitude" /> <br />
Longitude: <input type="text" name="Longitude" />
</form>

<button onclick="getLocation()">Get Location</button><input type="submit" value="Submit" />

<p id="demo">Click the button to get your coordinates:</p>
<p id="demo2">Click the button to get your coordinates:</p>

<script>
var x=document.getElementById("demo");
var y=document.getElementById("demo2");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML=position.coords.latitude;  
  y.innerHTML=position.coords.longitude;    
  }
</script>

</body>
</html>
Matt Hansen
  • 424
  • 1
  • 6
  • 16

1 Answers1

2

You are not really saying what the problem is, but as far as I know innerHTML only works in FF and not IE. Try:

function showPosition(position) {
  x.value=position.coords.latitude;  
  y.value=position.coords.longitude;    
}

Working example as requested in the comments

<!DOCTYPE html>
<html>
<body>

<form>
Latitude: <input id="demo" type="text" name="Latitude" /> <br />
Longitude: <input id="demo2" type="text" name="Longitude" />
</form>

<button onclick="getLocation()">Get Location</button><input type="submit" value="Submit" />

<p>Click the button to get your coordinates:</p>
<p id="demo2">Click the button to get your coordinates:</p>

<script>
var x=document.getElementById("demo");
var y=document.getElementById("demo2");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.value=position.coords.latitude;  
  y.value=position.coords.longitude;    
  }
</script>

</body>
</html>
Pieter
  • 2,188
  • 20
  • 27
  • Sorry for being unclear, but your solution worked! Changing innerHTML to value, then moving the id="demo" attribute to the tags got the latitude/longitude data into the input boxes. Thanks! – Matt Hansen Jan 30 '12 at 17:06
  • Please can we have a complete working example... Changing to the function above does not work in the example code in the question. – andrebruton Jul 17 '21 at 18:13
  • @andrebruton Updated. This is many years old and a better approach should be used although this still works. – Pieter Jul 27 '21 at 14:10