html 5 location

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Vegan
Forum Regular
Posts: 574
Joined: Fri Sep 05, 2008 3:34 pm
Location: Victoria, BC
Contact:

html 5 location

Post 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>
Hardcore Games™ Legendary is the Only Way to Play™
My site is powered by LAMP
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: html 5 location

Post 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.
User avatar
Vegan
Forum Regular
Posts: 574
Joined: Fri Sep 05, 2008 3:34 pm
Location: Victoria, BC
Contact:

Re: html 5 location

Post 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....
Hardcore Games™ Legendary is the Only Way to Play™
My site is powered by LAMP
Post Reply