-1

I've just started experimenting with Geolocation in web pages.

I've found the useful code snippet on W3Schools (http://www.w3schools.com/html/html5_geolocation.asp) which works.

What I'm a bit perplexed about though, is that IF i put the block (minus the tags) in a separate .js file, call the js file in the of my page, the code doesn't work at all. Why is this?

I'd like to have the final working code in its own .js file tht I can reference from any page.

The js file is in the same folder as the htm/php file

As soon as I revert the script into the body of my page, it works. Could someone help me understand the cause for this please? (If it makes a difference, I'm using Firefox 20


index.php

<!DOCTYPE html>
    <html>
    <head>
    <script type="application/javascript" src="geo.js"></script>

    <title>
        TEST 3: GeoLocation
    </title>
    </head>
    <body>
    <p id="demo">Click the button to get your coordinates:</p>
    <button onclick="getLocation()">Try It</button>
    </body>
</html>

geo.js

var x=document.getElementById("demo");

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;    
}
4

2 回答 2

0

我有同样的问题。变量 x 始终为空。我认为这是因为当您将外部 js 文件添加到标头时,局部变量 x 为空,因为它引用的元素尚未创建。

尝试添加

<script type="text/javascript" language="javascript"> x = document.getElementById("demo"); </script>

到 ID 为“demo”的元素下方的主体。

它对我有用!

于 2013-11-24T11:35:12.550 回答
0
于 2013-04-11T13:59:30.373 回答