I'm trying to get more familiar with HTML5. I am an experienced programmer, but a javascript neophyte. I've written some code to getCurrentPosition (which results in an async callback when the position is fixed). Here's the code (I already tested for, and got a positive response on, support for geolocation on this platform):
function tryGeo() {
document.write("asking for location <br>");
try {
navigator.geolocation.getCurrentPosition(savePos);
} catch (e) {
document.write("Excpn in asking for location <br>");
}
document.write("have asked for location <br>");
}
When that code runs, it pops up the permission request window or dialog. I grant permission. This is on Firefox 3.6.8 on MacOS 10.6.7.
Some time later, the callback to savePos() happens (when the position is known):
function savePos(pos) {
lat = pos.coords.latitude;
lon = pos.coords.longitude;
document.write("have got location lat " +lat+ ", lon " +lon+ " <br>");
}
The problem I'm having is that that document.write() moves to a new blank page. Instead,开发者_Go百科 I want to add the text to the page I was rendering when I make the getCurrentPosition() request. How can I do that?
I'm probably making some trivial beginner's error - please let me know what.
Also, links to "learn javascript for Experienced Coders" resources would be appreciated. Thaks,
Peter
That's just how document.write
works:
Writing to a document that has already loaded without calling
document.open()
will automatically perform adocument.open
call.
And document.open
:
If a document exists in the target, this method clears it.
And their example just above that note:
// In this example, the document contents are
// overwritten as the document
// is reinitialized on open().
document.write("<html><p>remove me</p></html>");
document.open();
// document is empty.
The easiest thing to do is to have an element already on the page and then update that element's content. So, you'd have a bit of HTML:
<p id="you-are-here"></p>
And then in the callback:
document.getElementById('you-are-here').innerHTML = "have got location lat " + lat + ", lon " + lon;
So, yeah, your trivial beginner's error is using document.write
on a document that has already loaded.
精彩评论