Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple example of using geolocation in HTML5
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPlbegz3bhu9AnJDCLWsOZM8jF3Hpp8tI&sensor=false"></script>
<script>
$(document).ready(function() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var str = 'Latitude: ' + position.coords.latitude.toString() + ' deg<br>' +
'Longitude: ' + position.coords.longitude.toString() + ' deg<br>';
str += "Accuracy: " + position.coords.accuracy.toString() + ' meters<br>';
if(position.coords.altitude) {
str += "Altitude: " + position.coords.altitude.toString() + ' meters<br>' +
"Altitude Accuracy: " + position.coords.altitudeAccuracy.toString() + ' meters<br>';
} else {
str += "Altitude: undefined<br>" ;
}
str += "Heading: " + (position.coords.heading ? position.coords.heading.toString() + ' deg<br>' : 'undefined<br>');
str += "Speed: " + (position.coords.speed ? position.coords.speed.toString() + ' m/s<br>' : 'undefined<br>');
var d = new Date(position.timestamp);
str += " <br>Timestamp " + d.toLocaleTimeString() + ' ' + d.toLocaleDateString();
$('#coordinates').html(str);
drawMap(position.coords.latitude, position.coords.longitude);
}, function() {
$('#coordinates').html('Error: The Geolocation service failed.');
});
} else {
$('#coordinates').html('Error: Your browser does not support Geolocation.');
}
});
function drawMap(latitude, longitude) {
var pos = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 16,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'You are here'
});
}
</script>
<style>
#map_canvas {
width: 300px;
height: 300px;
}
</style>
<div id='coordinates'></div>
<br>
<div id='map_canvas'></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment