Created
May 28, 2015 18:07
-
-
Save rafaelfoster/781419ca89663ac17e64 to your computer and use it in GitHub Desktop.
HTML5 Geolocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="viewport" content="width=device-width"> | |
<title>Get geolocation every second</title> | |
<script> | |
var getCurrentPositionRequest = 0; | |
function getTime() { | |
var now = new Date(); | |
var time = '' + now.getUTCHours() + ':'; | |
if (now.getUTCMinutes() < 10) time += '0'; | |
time += now.getUTCMinutes() + ':'; | |
if (now.getUTCSeconds() < 10) time += '0'; | |
time += now.getUTCSeconds(); | |
//time += ':' + now.getUTCMilliseconds(); | |
return time; | |
} | |
function formatTime(date) { | |
var time = '' + date.getUTCHours() + ':'; | |
if (date.getUTCMinutes() < 10) time += '0'; | |
time += date.getUTCMinutes() + ':'; | |
if (date.getUTCSeconds() < 10) time += '0'; | |
time += date.getUTCSeconds(); | |
//time += ':' + date.getUTCMilliseconds(); | |
return time; | |
} | |
function display(message) { | |
var div = document.getElementById('consoleDisplay'); | |
div.innerHTML = message + div.innerHTML; | |
} | |
function getCurrentPosition() { | |
var id = getCurrentPositionRequest++; | |
console.log('getCurrentPosition start - request ' + id); | |
navigator.geolocation.getCurrentPosition( | |
function(position) { | |
console.log('getCurrentPosition success - request ' + id); | |
console.log(position); | |
display('<div>' + id + ' (received: ' + getTime() + ') (timestamp: ' + formatTime(new Date(position.timestamp)) + ') success</div>'); | |
}, | |
function(error) { | |
console.log('getCurrentPosition error - request ' + id); | |
console.log(error); | |
display('<div>' + id + ' ' + getTime() + ' ' + error.message + '</div>'); | |
}, | |
{ | |
timeout: 5000 + id, | |
maximumAge: Infinity, | |
enableHighAccuracy: true | |
} | |
); | |
} | |
setInterval(getCurrentPosition, 1000); | |
</script> | |
</head> | |
<body> | |
<h1>Get geolocation every second</h1> | |
<div id="consoleDisplay"></div> | |
</body> | |
</html> | |
html { | |
margin: 0; | |
padding: 0; | |
} | |
body { | |
margin: 0; | |
padding: 5px; | |
} | |
*, | |
body, | |
button { | |
font-family: Inconsolata,monospace; | |
font-size: 10px; | |
line-height: 1.3; | |
} | |
h1 { | |
font-size: 14px; | |
margin: 0 0 0.5em 0; | |
padding: 0; | |
} | |
button { | |
margin: 1em; | |
padding: 1em; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment