Page 1 of 1

html 5 location

Posted: Wed Feb 25, 2015 9:44 pm
by Vegan
trying to figure out why this code clears the page as drawn, and then shows the location fine

Code: Select all

<script>
//var x;
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        document.write("Geolocation is not supported by this browser.");
        document.writeln();
    }
}
function showPosition(position) {
    document.write("Latitude: " + position.coords.latitude + 
    "<br />Longitude: " + position.coords.longitude); 
    document.writeln();
}
document.write(showPosition(getLocation()));
document.writeln();
</script>

Re: html 5 location

Posted: Thu Feb 26, 2015 2:26 am
by requinix
You're calling too many functions at the wrong time and trying to document.write() in the wrong place.

1. getLocation() does not return anything. Don't call it as an argument to another function.
2. showPosition() does not return anything either. Don't call it as an argument to another function.
3. You can't write the location until showPosition(), being the callback you gave to getCurrentPosition(). Any time before that, you don't have the location information yet.

Just call getLocation().

And when this is working, stop using document.write and document.writeln and use the modern method: run this code on document load, then show the location by getting an element and changing it's contents.

Re: html 5 location

Posted: Sat Apr 18, 2015 12:19 pm
by Vegan
swinging the axe I now have

<p id="locale"></p>
<script>
var x = document.getElementById("locale");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

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

Then I changed <body id="body" dir="ltr" lang="en-us" onload="getLocation()">

and now I have a fill in the blank with lat long

so now the fun part

getCountry(lat, long); // this seems trivial but....