Search code examples
javascripthtmlgeolocationw3c-geolocation

Javascript/HTML5 Geolocation using external js file


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

Solution

  • From comment in question: Indeed it does. But on my server it doesnt at all. Could something on the server be causing this? Working Code: bit.ly/Yp0HUZ Non-Working Code (JS in external file): bit.ly/10VS7ZU –

    Referencing your links: Your button on your server is missing the id attribute id="btnTryIt". When you try to disable the null object, an exception is thrown and the code execution stops.