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