2

I'm trying to obtain the users location, then insert into two seperate <input> fields. The script works when trying to print to, <p id="lat"></p>. But not for the <input>.

<form>
    <input type="number" step="any" name="lat" id="lat" value="" />
    <input type="number" step="any" name="lng" id="lng" value="" />
</form>

<button onclick="getLocation()">Get current location</button>

<script>
    var x = document.getElementById("lat").value;
    var y = document.getElementById("lng").value;
    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>

What am I missing here? Have added .value to the end of the veriable, am wondering if its the data type and/or step values?

2 Answers 2

3

x doesn't have an innerHTML because x is equal to the string value held within your #lng element. It isn't equal to the element itself.

Rather than setting x and y to the value of each of your elements, set them to your elements themselves:

var x = document.getElementById("lat");
var y = document.getElementById("lng");

Then you can set the value using x.value and y.value (x.innerHTML or y.innerHTML):

x.value = "Geolocation is not supported by this browser.";

And:

function showPosition(position) {
    x.value = position.coords.latitude;
    y.value = position.coords.longitude;
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the quick reply, have tried that but its still not working. Is there a way I can log errors to the console?
@atoms you commented when I was editing my post. Please see my update.
perfect, many thanks James! Realise now I was repeating myself by setting the var.
1

just set x.value= position.coords.latitude;

and remove initialize x= document.getElementById("lat");

var x = document.getElementById("lat");
    var y = document.getElementById("lng");
    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;
    }

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.